Js-获取可用的处理器数量

这真的只是为了满足好奇心,看看是否有更好的方法来做到这一点。

在我的 Windows8机顶盒上,Node 的 process.env对象具有 NUMBER_OF_PROCESSORS属性,而在我的 Linux 机顶盒上则没有。

显然,不同的平台具有不同的环境变量,这是已知的,但是无论如何,NUMBER _ OF _ PROCESSORS 似乎都是一个有用的东西。

我对 Linux 的快速修复是生成一个子进程来运行 nproc命令,但是我希望避免使用回调来简单地获取处理器的数量。看来一定有更简单的办法。

其他人做了什么来解决这个问题?

44935 次浏览

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.

const os = require('os'),
const cpuCount = os.cpus().length;

In your CLI you can run the following log the # of cores on the machine.

node -e 'console.log(require("os").cpus().length)'