What is physical-cpu-count?
The physical-cpu-count npm package is a simple utility that allows you to determine the number of physical CPU cores on your machine. This can be useful for optimizing performance, managing resources, or simply gathering system information.
What are physical-cpu-count's main functionalities?
Get Physical CPU Count
This feature allows you to retrieve the number of physical CPU cores on your machine. The code sample demonstrates how to use the package to log the number of physical CPU cores to the console.
const physicalCpuCount = require('physical-cpu-count');
console.log(`Number of physical CPU cores: ${physicalCpuCount}`);
Other packages similar to physical-cpu-count
os
The 'os' module is a built-in Node.js module that provides operating system-related utility methods and properties. It includes a method called 'os.cpus()' which returns an array of objects containing information about each logical CPU core. While it does not directly provide the number of physical CPU cores, you can use it to get detailed information about each core and infer the physical core count.
systeminformation
The 'systeminformation' package is a comprehensive library for retrieving system and hardware information. It provides detailed information about the CPU, including the number of physical and logical cores. Compared to 'physical-cpu-count', 'systeminformation' offers a broader range of system information but may be more complex to use for just retrieving the physical CPU count.
cpu-count
The 'cpu-count' package is another simple utility for retrieving the number of CPU cores. It provides both the number of logical and physical cores. Compared to 'physical-cpu-count', it offers similar functionality but includes logical core count as well.
physical-cpu-count
Returns the number of physical CPU cores.
Example
const physicalCpuCount = require('physical-cpu-count')
const logicalCpuCount = require('os').cpus().length
Use Case
Working with clusters of Node.js processes it is common to see code using os.cpus().length
as the number of child workers to fork. For some workloads this can negatively impact performance on CPUs that use simultaneous multithreading (SMT). Latency is doubled because two processes share the same physical CPU core to get their work done. Additionally there is memory spent for each running worker, as well as time to spawn their processes. It is better to fork no more child processes than there are physical cores.
Known Limitations
Implemented for Linux, macOS, and Windows.
Other platforms use a naive approach that only looks at Intel CPUs, and assumes every Intel CPU supports, and has enabled, Hyper-Threading with two threads per physical core. These assumptions are not always correct.
Power management might also make CPU cores unavailable.
See also: