Get number of CPU cores in JavaScript?

JavascriptWeb WorkerCpu Cores

Javascript Problem Overview


Is there a way to determine the number of available CPU cores in JavaScript, so that you could adjust the number of web workers depending on that?

Javascript Solutions


Solution 1 - Javascript

Yes. To quote MDN:

> The navigator.hardwareConcurrency read-only property returns the number of logical processors available to run threads on the user's computer… > > Modern computers have multiple physical processor cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may offer eight logical processor cores, for example. The number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch. > > The browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of Workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system.

It's supported by every browser except Internet Explorer. For that, you can use the polyfill core-estimator (demo, blog post).

Solution 2 - Javascript

No, there isn't, unless you use some ActiveX.

Solution 3 - Javascript

Solution 4 - Javascript

Here's a fairly quick concurrency estimator I hacked together... it hasn't undergone much testing yet:

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

Here's the code the workers run (since I have a jsfiddle link a sample is necessary):


// 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 estimator has a large number of workers run for a short period of time (4ms) and report back the times that they ran (unfortunately, performance.now() is unavailable in Web Workers for more accurate timing). The main thread then checks to see the maximum number of workers that were running during the same time. This test is repeated a number of times to get a decent sample to produce an estimate with.

So the main idea is that, given a small enough chunk of work, workers should only be scheduled to run at the same time if there are enough cores to support that behavior. It's obviously just an estimate, but so far it's been reasonably accurate for a few machines I've tested -- which is good enough for my use case. The number of samples can be increased to get a more accurate approximation; I just use 10 because it's quick and I don't want to waste time estimating versus just getting the work done.

Solution 5 - Javascript

If you are going to do data crunching on your workers, navigator.hardwareConcurrency might not be good enough as it returns the number of logical cores in modern browsers, you could 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}`);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontsauerweinView Question on Stackoverflow
Solution 1 - JavascriptEli GreyView Answer on Stackoverflow
Solution 2 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 3 - JavascriptrashtaoView Answer on Stackoverflow
Solution 4 - JavascriptdlongleyView Answer on Stackoverflow
Solution 5 - JavascriptDarioView Answer on Stackoverflow