【问题标题】:Get process CPU usage in percentage以百分比获取进程 CPU 使用率
【发布时间】:2020-11-27 02:11:06
【问题描述】:

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

【问题讨论】:

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


【解决方案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;
}

【讨论】:

    【解决方案2】:

    您可以使用附加的 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 核心分离的其他线程中运行。

    来源:

    【讨论】:

    • CPU Usage (%): 2277.5823913285444 CPU Usage (%): 2343.7592809543803 CPU Usage (%): 2510.3689922995127 在 Windows 上似乎无法正确获取百分比
    【解决方案3】:

    在回答之前,我们需要注意几个事实:

    • 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;现在我应该修复它。请注意,top 的 %CPU 是针对单个 CPU 的,如果进程使用多个单个 CPU,则该值可能会增加到 100% 以上
    【解决方案4】:

    另一种选择,假设您在 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 语句为特定操作系统设置正确的命令。

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 2011-10-10
      • 2012-10-19
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      相关资源
      最近更新 更多