将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 :)
谢谢.
推荐答案
根据文档,times
是
一个对象,其中包含花在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("\t", type, Math.round(100 * cpu.times[type] / total));
}
}
编辑:正如Tom Frost在评论中所说,这是自系统启动以来的平均使用量.这与问题是一致的,因为iostat
也是如此.但是,iostat
可以选择进行定期更新,显示自上次更新以来的平均使用量.汤姆的方法可以很好地实现这一目标.
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屋!