[英]How to get properly information about CPU usage?
I want to get a few metrics from my NodeJS app like cpuUsage
for user, system and as total usage.我想从我的
cpuUsage
应用程序中获取一些指标,例如用户、系统的 cpuUsage 和总使用量。 Below is my simple code:下面是我的简单代码:
private lastCpuUsage = process.cpuUsage();
getCpuUsage() {
const cpuUsage = process.cpuUsage();
const userUsageMicros = cpuUsage.user - this.lastCpuUsage.user;
const systemUsageMicros = cpuUsage.system - this.lastCpuUsage.system;
this.lastCpuUsage = cpuUsage;
console.log({
cpuUserUsage: userUsageMicros / 1e6, //1000000
cpuSystemUsage: systemUsageMicros / 1e6,
cpuTotalUsage: (userUsageMicros + systemUsageMicros) / 1e6
})
}
and here is a sample output:这是一个示例 output:
{
"cpuUserUsage": 0.016,
"cpuSystemUsage": 0.031,
"cpuTotalUsage": 0.047
}
And now I've got two questions:现在我有两个问题:
Thanks for any help!谢谢你的帮助!
If all the CPUs are in the same spec and processes are using only one CPU, then try with os
module.如果所有 CPU 都在同一规格中,并且进程只使用一个 CPU,则尝试使用
os
模块。 Node OS节点操作系统
const os = require('os');
const [cpu] = os.cpus();
const total = Object.values(cpu.times).reduce(
(acc, val) => acc + val, 0
);
const { user, system } = process.cpuUsage();
const percentage = 100 * 1000 * (user + system) / total ;
console.log(percentage);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.