将 Node.js 中 os.cpus() 的输出转换为百分比 [英] Convert the output of os.cpus() in Node.js to percentage
问题描述
有没有办法将 os.cpus() 信息转换为百分比?就像 iostat 的输出(在 CPU 部分).
Is there a way to convert the os.cpus() info to percentage? Just like the output of iostat (on the CPU section).
我的代码:
var os = require('os');
console.log(os.cpus());
输出:
[ { model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 5264280,
nice: 0,
sys: 4001110,
idle: 58703910,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 2215030,
nice: 0,
sys: 1072600,
idle: 64657440,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 5973360,
nice: 0,
sys: 3197990,
idle: 58773760,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 2187650,
nice: 0,
sys: 1042550,
idle: 64714820,
irq: 0 } } ]
我想将时间"指标转换为百分比,就像 iostat
命令中显示的那样:
I would like to have the "times" metric converted to percentage, just like is show on the iostat
command:
cpu
us sy id
6 3 91
我知道 nodejs 函数中的值是以 CPU 计时为单位的,但我不知道应该使用什么公式将它们转换为百分比:)
I understand that the values in the nodejs function are in CPU ticks, but I have no idea what formula should I use to convert them to percentage :)
谢谢.
推荐答案
根据文档,次
是
一个对象,包含花费在的 CPU 滴答数:user、nice、sys、idle 和 irq
an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq
所以你应该能够将时间相加并计算百分比,如下所示:
So you should just be able to sum the times and calculate the percentage, like below:
var cpus = os.cpus();
for(var i = 0, len = cpus.length; i < len; i++) {
console.log("CPU %s:", i);
var cpu = cpus[i], total = 0;
for(var type in cpu.times) {
total += cpu.times[type];
}
for(type in cpu.times) {
console.log(" ", type, Math.round(100 * cpu.times[type] / total));
}
}
正如 Tom Frost 在评论中所说,这是自系统启动以来的平均使用量.这与问题一致,因为 iostat
也是如此.但是,iostat
可以选择定期更新,显示自上次更新以来的平均使用情况.Tom 的方法可以很好地实现它.
As Tom Frost says in the comments, this is the average usage since system boot. This is consistent with the question, since the same is true of iostat
. However, iostat
has the option of doing regular updates, showing the average usage since the last update. Tom's method would work well for implementing that.
这篇关于将 Node.js 中 os.cpus() 的输出转换为百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!