Skip to content

Instantly share code, notes, and snippets.

@bag-man
Last active May 5, 2024 22:16
Show Gist options
  • Save bag-man/5570809 to your computer and use it in GitHub Desktop.
Save bag-man/5570809 to your computer and use it in GitHub Desktop.
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 = 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.");
}, 100);
@luokuning
Copy link

Here is a way that console every single cpu average load:

const os = require('os')

function delta() {
  const cpus = os.cpus()

  return cpus.map(cpu => {
    const times = cpu.times
    return {
      tick: Object.keys(times).filter(time => time !== 'idle').reduce((tick, time) => { tick+=times[time]; return tick }, 0),
      idle: times.idle,
    }
  })
}

let startMeasures = delta()
setInterval(() => {
  const endMeasures = delta()
  const percentageCPU = endMeasures.map((end, i) => {
    return ((end.tick - startMeasures[i].tick) / (end.idle - startMeasures[i].idle) * 100).toFixed(3) + '%'
  })

  console.log(percentageCPU.join(' '), '\n')

  // reset
  startMeasures = delta()
}, 2000)

@OussamaRomdhane
Copy link

OussamaRomdhane commented Mar 8, 2018

Hi mate, great gist.
This line of code though seems a bit ambiguous to me:
https://gist.github.com/bag-man/5570809#file-cpu-js-L43
I get that you're trying to get rid of the fractional-part but couldn't you just use Math.floor or Math.rand? I say that only for readability/maintainability reasons.

@adrwh
Copy link

adrwh commented Dec 14, 2018

Noob <, however how can i use this with chart.js?

@GaetanoPiazzolla
Copy link

GaetanoPiazzolla commented Nov 8, 2019

Here is a way to get the medium load every N milliseconds, checking the load every M milliseconds.
Also, I've used promise style asynch programming.
https://gist.github.com/GaetanoPiazzolla/c40e1ebb9f709d091208e89baf9f4e00

@aggregate1166877
Copy link

aggregate1166877 commented Aug 27, 2020

I rewrite it like closure function:

That looks damn beautiful - but I can't get it to work. What's that style called? What kind of processor / compiler do you need for that?

@GaetanoPiazzolla
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment