Create a gist now

Instantly share code, notes, and snippets.

@bag-man /cpu.js
Last active Jan 10, 2017

How to calculate the current CPU load with Node.js; without using any external modules or OS specific calls.
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 = -;
//Calculate the average percentage CPU usage
var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
//Output result to console
console.log(percentageCPU + "% CPU Usage.");
}, 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.

four43 commented Oct 31, 2014

For others who landed here via Google search: Node now has a os.loadavg() method you can find at: Which is much simpler.


Both of the above comments miss the point of this gist entirely... totalTick is divided by cpus.length (i.e. the number of cpus) and os.loadavg() will give the average load not the instantaneous... Excellent gist, just need to understand what you are looking at


Hi, thanks for the trick, i have just to notice that start Measure variable should be updated after calculating the percentage CPU so we can get the percentage CPU for the last time interval, in your case 100 milliseconds. the actual code is calculating the percentage CPU for all the time the device is up and it's wrong.

Have just to add :
startMeasure = cpuAverage();
after line 43:
var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);


I rewrite it like closure function:

os = require 'os'

cpuAverage = ->
    totalIdle = 0
    totalTick = 0

    cpus = os.cpus()

    for cpu in cpus
        for type of cpu.times
            totalTick += cpu.times[type]

        totalIdle += cpu.times.idle

    idle    = totalIdle / cpus.length
    total   = totalTick / cpus.length

    return {

 * @return {Object} dif - difference of usage CPU
 * @return {Float}  dif.idle
 * @return {Float}
 * @return {Float}  dif.percent
cpuLoadInit = =>
    start = cpuAverage()
    return ->
        end = cpuAverage()
        dif = {}

        dif.idle  = end.idle  - start.idle = -

        dif.percent = 1 - dif.idle /

        return dif

cpuLoad = cpuLoadInit()

module.exports = {


cpu = require './lib/cpu.js'

load = cpu.cpuLoad()
console.log load
  idle: 71429,
  percent: 0.09731516059118284,
  total: 79129.5
astroza commented Jan 10, 2017 edited

If you need integrate this in your application to get the average load in the past X milliseconds:

function CPULoad(avgTime, callback) {
  this.samples = [];
  this.samples[1] = cpuAverage();
  this.refresh = setInterval(() => {
    this.samples[0] = this.samples[1];
    this.samples[1] = cpuAverage();
    var totalDiff = this.samples[1].total - this.samples[0].total;
    var idleDiff = this.samples[1].idle - this.samples[0].idle;
    callback(1 - idleDiff / totalDiff);
  }, avgTime);

// load average for the past 1000 milliseconds
var load = CPULoad(1000, (load) => console.log((100*load).toFixed(1)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment