获取进程CPU使用率百分比

时间:2020-08-06 18:46:29

标签: javascript node.js process cpu-usage percentage

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

4 个答案:

答案 0 :(得分:4)

另一种选择,假设您在linux / macos O.S下运行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语句为特定的操作系统设置正确的命令。

答案 1 :(得分:3)

您可以使用附加的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更多的时间,因为调用可以在与NodeJS核心分开的其他线程中运行。

来源:

答案 2 :(得分:1)

在回答之前,我们需要注意一些事实:

  • 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的值,而不是将其打印到控制台。

答案 3 :(得分:1)

尝试使用以下代码获取%的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调整为以下内容,以检查是否可以解决您的问题。

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