繁体   English   中英

尝试获取节点进程的标准化 CPU 使用率

[英]Trying to get normalized CPU usage for node process

我正在尝试计算我的节点进程的标准化 cpu 百分比。 我的目标是让它与我在htop中的 pid 输出相匹配,但我无法这样做。 下面是我的代码以及我的 htop 输出。

import { cpuUsage } from "node:process";
import { cpus } from "os";

function basicCpuUsage() {
  const startTime = process.hrtime();
  const startUsage = cpuUsage();
  const numCpus = cpus().length;

  const add = 1 + 1; // make cpu do work?

  const usageDiff = cpuUsage(startUsage); // get diff time from start
  const endTime = process.hrtime(startTime); // total amount of time that has elapsed
  const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
  const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;

  const cpuPercent = (usageMS / totalMS) * 100;
  const normTotal = usageMS / numCpus; // average usage time per cpu
  const normPercent = (normTotal / totalMS) * 100;

  console.log({
    cpuPercent: cpuPercent.toFixed(2),
    normPercent: normPercent.toFixed(2),
  });
}

process.title = "CPU Test";
const { pid } = process;
console.log({ pid });
const title = setInterval(() => {
  basicCpuUsage();
}, 1000);

这是我的输出,您可以看到我的代码 cpu 输出与我的 htop cpu 输出不匹配。 我的计算哪一部分不正确? 我在想这可能与我的setInterval函数调用有关,但不确定。 我正在尝试创建一个长时间运行的进程,我可以在其中查看 cpu 使用情况。

顶层输出

结果我计算错了。 当我应该做一次时,我将我的totalTimeMS划分了两次。 此外,我将 currentUsage 和 currentTime 移到了函数的外部。

下面是正确的计算:

import { cpus } from "os";

let currentUsage = process.cpuUsage();
let currentTime = process.hrtime();

function basicCpuUsage() {
  const numCpus = cpus().length;

  const usageDiff = process.cpuUsage(currentUsage); // get diff time from start
  const endTime = process.hrtime(currentTime); // total amount of time that has elapsed

  currentUsage = process.cpuUsage()
  currentTime = process.hrtime();

  const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
  const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;

  const cpuPercent = (usageMS / totalMS) * 100;
  const normPercent = (usageMS / totalMS / numCpus) * 100; // average usage time per cpu

  console.log({
    cpuPercent: cpuPercent.toFixed(2),
    normPercent: normPercent.toFixed(2),
  });
}

process.title = "CPU Test";

setInterval(() => {
 for (let i = 0; i < 25; i++) {
    const add = 1 + 1;
  }
  basicCpuUsage();
}, 5000);

CPU使用率

暂无
暂无

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

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