Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Get number of processors available

Tags:

linux

node.js

This is really just to satisfy curiosity, and see if there's a better way to do this.

On my Windows 8 box, Node's process.env object has a NUMBER_OF_PROCESSORS property, on my Linux box it doesn't.

Obviously different platforms have different environment variables, that much is a given, but it seems like NUMBER_OF_PROCESSORS would be a useful thing to have regardless.

My quick fix for Linux was spawning a child process to run the nproc command, but I'd like to avoid using a callback for simply getting the number of processors. Seems like there must be a simpler way.

What have other people done to solve this?

like image 840
LouisK Avatar asked Sep 25 '14 22:09

LouisK


People also ask

How do I know my number of processors?

Open Device Manager (in the search box of the taskbar, type in "Device Manager", then select Open) Click on ">" to expand the Processors section. Count the number of entries to get the number of logical processors.

What command counts number of logical CPUs node JS?

To get information about a system's CPU's, we will use the os. cpu() method that will return an array of objects with information about each CPU in it.

How many CPUs does a node have?

A node with 2 CPU-chips and 16 CPU-cores per CPU-chip can be used to carry out 32 tasks simultaneously. A job can be run on a single CPU-core, but if your code is modified to support parallel operations, a job may also run on multiple CPU-cores on one or more CPU-chips, and even on multiple nodes at one time.

How do I know how many virtual processors I have?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.


2 Answers

It's built into node and called os.cpus()

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).

The length of this array is the number of "processors" in the system. Most systems only have one CPU, so that's the number of cores of that CPU.

See the code below:

const os = require('os') const cpuCount = os.cpus().length 
like image 145
Yogu Avatar answered Sep 28 '22 04:09

Yogu


var os = require('os'), cpuCount = os.cpus().length; 
like image 22
rainabba Avatar answered Sep 28 '22 06:09

rainabba