public
Last active

How to calculate the current CPU load with Node.js; without using any external modules or OS specific calls.

  • Download Gist
cpu.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
var os = require("os");
 
//Create function to get CPU information
function cpuAverage() {
 
//Initialise sum of idle and time of cores and fetch CPU info
var totalIdle = 0, totalTick = 0;
var cpus = os.cpus();
 
//Loop through CPU cores
for(var i = 0, len = cpus.length; i < len; i++) {
 
//Select CPU core
var cpu = cpus[i];
 
//Total up the time in the cores tick
for(type in cpu.times) {
totalTick += cpu.times[type];
}
 
//Total up the idle time of the core
totalIdle += cpu.times.idle;
}
 
//Return the average Idle and Tick times
return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};
}
 
//Grab first CPU Measure
var startMeasure = cpuAverage();
 
//Set delay for second Measure
setTimeout(function() {
 
//Grab second Measure
var endMeasure = cpuAverage();
 
//Calculate the difference in idle and total time between the measures
var idleDifference = endMeasure.idle - startMeasure.idle;
var totalDifference = endMeasure.total - startMeasure.total;
 
//Calculate the average percentage CPU usage
var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
 
//Output result to console
console.log(percentageCPU + "% CPU Usage. Maybe.");
 
}, 100);

You're tracking ticks across all cores but totaling their average. That doesn't seem right. cpuAverage should probably take a core number as an argument so it can be used to average load per core.

cpuAverage will eventually overflow totalIdle and totalTicks. You should look into limiting those on a one-time (yuck) or continual (yay!) basis.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.