简体   繁体   English

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

[英]Get process CPU usage in percentage

The process.cpuUsage() function displays some weird microsecond values. process.cpuUsage() function 显示了一些奇怪的微秒值。 How to get cpu usage in percentage?如何以百分比获取cpu使用率?

You can achieve this using the additional os native module to get informations about your CPUs:您可以使用附加的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}`);

If you want to get the global CPU usage (taking all your CPUs into account), you need to accumulate every times of every CPUs, not only the first one, but that should be less useful in most cases.如果要获取全局 CPU 使用率(考虑到所有 CPU),则需要累积每个 CPU 的每次,不仅是第一个,而且在大多数情况下应该不太有用。

Note that only the "system" time can use more than the first CPU because the calls can run in other threads separated from the NodeJS core.请注意,只有“系统”时间才能使用比第一个 CPU 更多的时间,因为调用可以在与 NodeJS 核心分离的其他线程中运行。

Sources:资料来源:

An alternative, assuming you are running node under linux/macos OS is:另一种选择,假设您在 linux/macos 操作系统下运行节点是:

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();

If your OS is windows, your command must be different.如果您的操作系统是 windows,则您的命令必须不同。 As i'm not running windows i can't tell to you the exact command, but you can start from here:由于我没有运行 windows 我不能告诉你确切的命令,但你可以从这里开始:

tasklist任务列表

get-process 获取过程

WMIC WMIC

You can also check the platform with process.platform and do an if/else statment setting the right command for the specific OS.您还可以使用process.platform检查平台并执行 if/else 语句,为特定操作系统设置正确的命令。

Before answering we need to take care about a couple of facts:在回答之前,我们需要注意几个事实:

  • Node.js does not uses only one CPU, but every async I/O operation may use additional CPUs Node.js 不只使用一个 CPU,但每个异步 I/O 操作可能会使用额外的 CPU
  • the times returned by process.cpuUsage are cumulative of all CPUs used by the Node.js process process.cpuUsage返回的时间是 Node.js 进程使用的所有 CPU 的累积时间

so to calculate the CPU usage of Node.js considering all the CPUs of the host, we could use something similar to:因此,要考虑主机的所有 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);

or we can read the value of lastUsage from where we need it rather printing it to the console.或者我们可以从需要的地方读取lastUsage的值,而不是将其打印到控制台。

Try using the below code to get cpu usage in %尝试使用下面的代码来获取以 % 为单位的 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
}

try tweaking the secNSec2ms function to the following to check if it solves your problem.尝试将secNSec2ms function调整为以下内容,以检查它是否可以解决您的问题。

function secNSec2ms(secNSec) {
  if (Array.isArray(secNSec))
  return secNSec[0] * 1000 + secNSec[1] / 1000000 return secNSec / 1000;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM