我试图计算我的节点进程的标准化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使用情况。
1条答案
按热度按时间oknrviil1#
原来我做了一个不正确的计算。我把我的
totalTimeMS
除以两次,而我应该做一次。另外,我把currentUsage和currentTime移到了函数外面。以下是正确的计算方法: