How to Detect Number of Processor Cores with Javascript

javascript
Published on November 6, 2019

The number of available logical processor cores in the device can be found with the navigator.hardwareConcurency Javascript property. This number can be useful in knowing how many Web Workers can be executed in parallel.

The number of hardware cores in a processor represents the number of threads that the processor can execute in parallel. A processor having only a single core can run one thread and so perform only one operation at one time. A processor having two cores can run two threads, so perform two operations in parallel. An so on.

Modern processors are capable of executing more than one thread in a single physical core through hyperthreading. A single physical core can even run multiple threads on it. So a single physical core may become multiple logical cores (2 physical cores may in total become 4 logical cores). Each logical core can run one thread, and all logical cores can run in parallel.

In Javascript the number of logical processors available in a device can be detected using the navigator.hardwareConcurency property. As the name indicates this provides the number of concurrent processor threads that can be run by the the browser.

// gets the "available" logical processors count
let logicalProcessorCount = navigator.hardwareConcurrency;

It is important not to treat this count as the actual number of logical cores present in the device. Depending upon various factors such as the number of cores used up, or the number of cores actually available for work, browser may return a lower number of logical cores.

Demo

The current device has logical cores

Why Get the Number of CPU Cores with Javascript ?

Javascript is single threaded — it executes only on a single processor thread. It has asynchronous features, but those are still executed in the same processor thread (using Javascript's event-loop).

However recent updates to Javascript have introduced Web Workers. Web Workers are executed in parallel, each in a separate processor thread.

So navigator.hardwareConcurency can be useful in knowing the limit of Web Workers that can be executed by the application at a single time.

In this Tutorial