Get the number of processor cores in JavaScript?

Is there a way to determine the number of processor cores available in JavaScript so that you can adjust the number of web workers based on this?

+52
javascript web-worker cpu-cores
Jul 20 '10 at 11:35
source share
6 answers

Yes, navigator.hardwareConcurrency . Supported natively in Chrome, Firefox, Edge, Opera, and Webkit; Supported in all browsers with a polyfill .

+66
May 17 '14 at 1:04
source share

No, no, if you are not using any ActiveX.

+19
Jul 20 '10 at 11:37
source share
+14
Jun 07 '13 at 9:45
source share

Here is a pretty quick concurrency appraiser that I hacked together ... it hasn't passed many tests yet:

http://jsfiddle.net/Ma4YT/2/

Here's the code the workers are working on (since I have a jsfiddle link, a sample is needed):

// create worker concurrency estimation code as blob var blobUrl = URL.createObjectURL(new Blob(['(', function() { self.addEventListener('message', function(e) { // run worker for 4 ms var st = Date.now(); var et = st + 4; while(Date.now() < et); self.postMessage({st: st, et: et}); }); }.toString(), ')()'], {type: 'application/javascript'})); 

The evaluator has a large number of workers executed in a short period of time (4 ms) and reports on the time in which they were performed (unfortunately, the performance.now () function is not available in Web Workers to more accurately determine the time). Then the main thread checks that the maximum number of workers who worked at the same time. This test is repeated several times in order to get a decent sample to get a score with.

Thus, the main idea is that, given the small amount of work, workers should plan to launch at the same time if there are enough cores to support this behavior. This is obviously just an estimate, but so far it has been accurate enough for the few machines I tested, which is good enough for my use. The number of samples can be increased to get a more accurate approximation; I just use 10 because it is fast and I don’t want to spend time evaluating, not just doing the work.

+11
Feb 17 '14 at 0:30
source share

If you intend to process the data of your employees, navigator.hardwareConcurrency may not be good enough, since it returns the number of logical cores in modern browsers, you can try to estimate the number of physical cores using WebCPU :

 import {WebCPU} from 'webcpu'; WebCPU.detectCPU().then(result => { console.log('Reported Cores: ${result.reportedCores}'); console.log('Estimated Idle Cores: ${result.estimatedIdleCores}'); console.log('Estimated Physical Cores: ${result.estimatedPhysicalCores}'); }); 
0
Apr 12 '19 at 17:00
source share

No. JavaScript is very far from such hardware details and does not have a legitimate mechanism to request them.

-2
Jul 20 '10 at 11:37
source share



All Articles