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

mnemlml8  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(175)

我试图计算我的节点进程的标准化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使用情况。

oknrviil

oknrviil1#

原来我做了一个不正确的计算。我把我的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);

相关问题