Skip to content

Instantly share code, notes, and snippets.

@GaetanoPiazzolla
Last active October 11, 2023 14:08
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save GaetanoPiazzolla/c40e1ebb9f709d091208e89baf9f4e00 to your computer and use it in GitHub Desktop.
Save GaetanoPiazzolla/c40e1ebb9f709d091208e89baf9f4e00 to your computer and use it in GitHub Desktop.
% CPU in Node.JS
const 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};
}
// function to calculate average of array
const arrAvg = function (arr) {
if (arr && arr.length >= 1) {
const sumArr = arr.reduce((a, b) => a + b, 0)
return sumArr / arr.length;
}
};
// load average for the past 1000 milliseconds calculated every 100
function getCPULoadAVG(avgTime = 1000, delay = 100) {
return new Promise((resolve, reject) => {
const n = ~~(avgTime / delay);
if (n <= 1) {
reject('Error: interval to small');
}
let i = 0;
let samples = [];
const avg1 = cpuAverage();
let interval = setInterval(() => {
console.debug('CPU Interval: ', i);
if (i >= n) {
clearInterval(interval);
resolve(~~((arrAvg(samples) * 100)));
}
const avg2 = cpuAverage();
const totalDiff = avg2.total - avg1.total;
const idleDiff = avg2.idle - avg1.idle;
samples[i] = (1 - idleDiff / totalDiff);
i++;
}, delay);
});
}
getCPULoadAVG(1000, 100).then((avg) => {
console.log(avg);
});
@Wqrld
Copy link

Wqrld commented May 28, 2020

This is to be honest the only right one i could find that actually gives a correct average

@felipebutcher
Copy link

Hey there! Thank you. This was the only one that I found that showed the same values as in htop. I created an NPM package with your code: https://github.com/felipebutcher/node-os-info

@GaetanoPiazzolla
Copy link
Author

Thank you Felipe, you are welcome.
Also you have been very kind linking this gist to your repository. :)

@Guitarman051120
Copy link

Sadly, in my case it just reports some random numbers. Still thank you

@felipebutcher
Copy link

Sadly, in my case it just reports some random numbers. Still thank you

@Guitarman051120 What OS are you using?

@jonlepage
Copy link

it give global os cpu usage, no current application usage
My os 12%
app 4%
this show 12%

@jonlepage
Copy link

bullshit
thetresurusebotlkgy

@GaetanoPiazzolla
Copy link
Author

Thank you @djmisterjon for your kind comment. Anyway, no one said that this gives information about the current nodejs application.
This gives information about CPU percentage occupation of the entire host.

@jhimy-michel
Copy link

thanks for sharing @GaetanoPiazzolla

@felipebutcher
Copy link

felipebutcher commented Sep 23, 2022

@djmisterjon Don't be an asshole dude. The author kindly shared his code which works. I use linux but I tested myself in Windows. You're are using nwjs which is a hack to run node inside a browser. This is not even a real node application. Of course it won't work.

@jonlepage
Copy link

jonlepage commented Sep 23, 2022

This is not even a real node application

what wrong with you, bullshit!

And why assault and insult people for free ?
Go health your brain and also look for your language young boy.

@felipebutcher
Copy link

@djmisterjon you came to the gist that the guy kindly shared and commented "bullshit". that's an asshole attitude. am i the one insulting people here? come on.

@The3ven
Copy link

The3ven commented Oct 11, 2022

Hey there! Thank you. This was the only one that I found that showed the same values as in htop. I created an NPM package with your code: https://github.com/felipebutcher/node-os-info

sir im used your npm module from your git!
i want to use it in my bot command but it support only callback values.
please help me to use it in a variable that i can pass that into my bot response.
like this:-

Total Memory : ${totalram}GB
Free Memory : ${totalfreeram}GB
Used Memory : ${total_used}GB

@abz98
Copy link

abz98 commented Feb 9, 2023

I tried different things but your code brings out the most accurate readings. I tried and tested it, Thanks, mate

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