Skip to content

Instantly share code, notes, and snippets.

@BytesCrafter
Created April 28, 2020 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BytesCrafter/02dc9734e42d17c266d3ef715877cc94 to your computer and use it in GitHub Desktop.
Save BytesCrafter/02dc9734e42d17c266d3ef715877cc94 to your computer and use it in GitHub Desktop.
Convert the output of os.cpus() in Node.js to percentage
// According to the http://nodejs.org/docs/latest/api/os.html#os_os_cpus, 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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment