Convert the output of os.cpus() in Node.js to percentage
This module, that caN be installed using NPM provides what you need:
https://github.com/oscmejia/os-utils
calle the cpuUsage(callback) method and you will get what you need.
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("\t", 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.