Get number of CPU cores in JavaScript?
Asked Answered
D

5

82

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?

Diet answered 20/7, 2010 at 11:35 Comment(4)
@meo: "This computer has huh? CPU cores." The average user knows even less about cores than JS does ;)Sunday
Why is it that everyone that writes a web page assumes they can take control of the full resources of my computer? I'd like to accomplish other things while I read the one tidbit of information I need from your web page.Philologian
@meo: Why I want to know this? If a system only has 1 or 2 cores and I start 4 web workers, the threads or processes (depending on how the browser implemented web workers) may block them selves. It is quite common that the number of threads you start depends on the number of available cores.Diet
There also has been a discussion about this in the WHATWG mailing list: lists.whatwg.org/pipermail/whatwg-whatwg.org/2009-November/… - lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-November/…Diet
G
110

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 now supported by every browser except Internet Explorer. For compatibility with older browsers, or to bypass misguided browser privacy restrictions on the resolution of this parameter, you can use the polyfill core-estimator (demo, blog post).

Georgie answered 17/5, 2014 at 1:4 Comment(6)
It's undefined when I run this in Chrome 35.Moke
It is available in the current Chrome Canary build according to src.chromium.org/viewvc/blink?view=revision&revision=175629 Confirmed worked in Chrome Canary 37.Incept
Is it a part of standard of some kind (like supported or meant to be supported in other browsers as well)?Celluloid
A safe bet is to use navigator.hardwareConcurrency || 4 to assume 4-thread capability on browsers that don't report it. Most CPUs support 4 or greater, even on mobile devices. On CPUs that have less, the 4 will simply be timesliced. Note that the thread count may be different from the number of cores in a CPU, as many CPUs support more than one thread per core. One Intel 2-core CPU will run 4 threads concurrently in hardware.Madai
You can view the full support table here: caniuse.com/#feat=hardwareconcurrencyInformality
Everything Greg Searly said is correct. This is a helpful answer even though it is incorrect. navigator.hardwareConcurrency returns the number of CPU optimized "threads" which is often but not always double the number of CPU cores. The core count would be much more useful for this question since matching the hyperthread count only pushes the CPU to do more context switching. More detail at: askubuntu.com/questions/668538/…Clunk
F
18

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

Flowery answered 20/7, 2010 at 11:37 Comment(2)
Though there are discussions in the WHATWG mailing list about providing a similar attribute in version 2 of the spec: lists.whatwg.org/pipermail/whatwg-whatwg.org/2009-November/… lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-November/…Diet
Finally there is a API for this, see the now accepted answer.Diet
V
14

You can try to estimate the number of cores with: https://github.com/oftn/core-estimator

demo: http://eligrey.com/blog/post/cpu-core-estimation-with-javascript

Veedis answered 7/6, 2013 at 9:45 Comment(0)
A
12

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.

Adamite answered 17/2, 2014 at 0:30 Comment(0)
B
2

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}`);
});
Brinkema answered 12/4, 2019 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.