Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

operating system - Convert the output of os.cpus() in Node.js to percentage

Is there a way to convert the os.cpus() info to percentage? Just like the output of iostat (on the CPU section).

My code:

var os = require('os');
console.log(os.cpus());

The output:

[ { 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 } } ]

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

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 :)

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the docs, times is

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));
    }
}

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...