以百分比形式获取进程的CPU使用率

14

process.cpuUsage() 函数显示的是一些奇怪的微秒值。如何获取 CPU 使用率的百分比?


这个回答解决了你的问题吗?通过NodeJS获取/查看内存和CPU使用情况 - rksh1997
请看这里:https://gist.github.com/bag-man/5570809 - Treast
谢谢Treast,我试过了,但它显示给我全局CPU使用情况。我只想获取当前进程使用的% CPU。 - Alex
1
试一下这个:https://www.npmjs.com/package/pidusage - Take-Some-Bytes
4个回答

10

你可以使用附加的os本地模块来获取关于你的CPU的信息:

const os = require('os');

// Take the first CPU, considering every CPUs have the same specs
// and every NodeJS process only uses one at a time.
const cpus = os.cpus();
const cpu = cpus[0];

// Accumulate every CPU times values
const total = Object.values(cpu.times).reduce(
    (acc, tv) => acc + tv, 0
);

// Normalize the one returned by process.cpuUsage() 
// (microseconds VS miliseconds)
const usage = process.cpuUsage();
const currentCPUUsage = (usage.user + usage.system) * 1000;

// Find out the percentage used for this specific CPU
const perc = currentCPUUsage / total * 100;

console.log(`CPU Usage (%): ${perc}`);

如果您想获取全局CPU使用率(考虑到所有CPU),则需要累加每个CPU的每个时间,而不仅仅是第一个CPU。但在大多数情况下,这应该没有太多用处。

请注意,只有“系统”时间可以使用超过第一个CPU,因为调用可以在与NodeJS核心分离的其他线程中运行。

Sources :


3
似乎在Windows上无法正确获取CPU使用率百分比。 CPU使用率(%):2277.5823913285444 CPU使用率(%):2343.7592809543803 CPU使用率(%):2510.3689922995127 - LeoPucciBr
当前CPU使用率 = (usage.user + usage.system) / 1000; 必须除以1000而不是乘以1000。 - Semmel
不同的操作系统之间似乎存在差异,请注意。 - bob6664569
这是只针对单个核心还是整个 CPU? - Kamuran Sönecek
这个例子仅适用于第一个CPU的使用(请注意代码下面的注释),如果需要,您可以迭代并计算所有CPU的平均值。 - bob6664569

6
假设你正在 Linux/MacOS 操作系统下运行 Node,另一种选择是:
var exec = require("child_process").exec;

function getProcessPercent() {

  // GET current node process id.
  const pid = process.pid;
  console.log(pid);

  //linux command to get cpu percentage for the specific Process Id.
  var cmd = `ps up "${pid}" | tail -n1 | tr -s ' ' | cut -f3 -d' '`;

  setInterval(() => {
    //executes the command and returns the percentage value
    exec(cmd, function (err, percentValue) {
      if (err) {
        console.log("Command `ps` returned an error!");
      } else {
        console.log(`${percentValue* 1}%`);
      }
    });
  }, 1000);
}

getProcessPercent();

如果您的操作系统是Windows,您的命令必须不同。由于我没有运行Windows,无法告诉您确切的命令,但您可以从这里开始:

tasklist

get-process

WMIC

您还可以使用 process.platform 检查平台,并使用 if/else 语句为特定的操作系统设置正确的命令。


4
在回答之前,我们需要注意以下几点:
  • Node.js 不仅使用一个 CPU,每个异步 I/O 操作都可以使用其他 CPU
  • process.cpuUsage 返回的时间是 Node.js 进程所使用的所有 CPU 的累计时间
因此,为了计算考虑主机上所有 CPU 的 Node.js 的 CPU 使用情况,我们可以使用类似以下的方法:
const ncpu = require("os").cpus().length;
let previousTime = new Date().getTime();
let previousUsage = process.cpuUsage();
let lastUsage;

setInterval(() => {
    const currentUsage = process.cpuUsage(previousUsage);

    previousUsage = process.cpuUsage();

    // we can't do simply times / 10000 / ncpu because we can't trust
    // setInterval is executed exactly every 1.000.000 microseconds
    const currentTime = new Date().getTime();
    // times from process.cpuUsage are in microseconds while delta time in milliseconds
    // * 10 to have the value in percentage for only one cpu
    // * ncpu to have the percentage for all cpus af the host

    // this should match top's %CPU
    const timeDelta = (currentTime - previousTime) * 10;
    // this would take care of CPUs number of the host
    // const timeDelta = (currentTime - previousTime) * 10 * ncpu;
    const { user, system } = currentUsage;

    lastUsage = { system: system / timeDelta, total: (system + user) / timeDelta, user: user / timeDelta };
    previousTime = currentTime;

    console.log(lastUsage);
}, 1000);

或者我们可以从需要的地方读取lastUsage的值,而不是将其打印到控制台。


我认为这个程序不正常。即使在空闲状态下,每隔两次调用CPU使用率都会更高。此外,值与“top”中的值不匹配。 - Alex
你是对的 @Alex;现在我应该已经修复了它。请注意,top命令中的%CPU是针对单个CPU的,如果进程使用多个CPU,则该值可能会超过100%。 - Daniele Ricci

3

尝试使用以下代码获取CPU的使用率(以百分比表示)

var startTime  = process.hrtime()
var startUsage = process.cpuUsage()

// spin the CPU for 500 milliseconds
var now = Date.now()
while (Date.now() - now < 500)

var elapTime = process.hrtime(startTime)
var elapUsage = process.cpuUsage(startUsage)

var elapTimeMS = secNSec2ms(elapTime)
var elapUserMS = secNSec2ms(elapUsage.user)
var elapSystMS = secNSec2ms(elapUsage.system)
var cpuPercent = Math.round(100 * (elapUserMS + elapSystMS) / elapTimeMS)

console.log('elapsed time ms:  ', elapTimeMS)
console.log('elapsed user ms:  ', elapUserMS)
console.log('elapsed system ms:', elapSystMS)
console.log('cpu percent:      ', cpuPercent)

function secNSec2ms (secNSec) {
  return secNSec[0] * 1000 + secNSec[1] / 1000000
}

尝试将 secNSec2ms函数 调整为以下内容,以检查是否解决了您的问题。
function secNSec2ms(secNSec) {
  if (Array.isArray(secNSec))
  return secNSec[0] * 1000 + secNSec[1] / 1000000 return secNSec / 1000;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接