-
-
Save bag-man/5570809 to your computer and use it in GitHub Desktop.
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); | |
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)));
I have slightly modified this script to get the average load for a single cpu
cpuIAverage = function(i) {
var cpu, cpus, idle, len, total, totalIdle, totalTick, type;
totalIdle = 0;
totalTick = 0;
cpus = os.cpus();
cpu = cpus[i];
for (type in cpu.times) {
totalTick += cpu.times[type];
}
totalIdle += cpu.times.idle;
idle = totalIdle / cpus.length;
total = totalTick / cpus.length;
return {
idle: idle,
total: total
};
};
and
cpuILoadInit = function() {
var index=arguments[0];
return function() {
var start;
start = cpuIAverage(index);
return function() {
var dif, end;
end = cpuIAverage(index);
dif = {};
dif.cpu=index;
dif.idle = end.idle - start.idle;
dif.total = end.total - start.total;
dif.percent = 1 - dif.idle / dif.total;
return dif;
};
};
};
where
cpuILoad = (function() {
var info=[],cpus = os.cpus();
for (i = 0, len = cpus.length; i < len; i++) {
var a=cpuILoadInit(i)();
info.push( a );
}
return function() {
var res=[],cpus = os.cpus();
for (i = 0, len = cpus.length; i < len; i++) {
res.push( info[i]() );
}
return res;
}
})();
I think it's easier than this, but it should print on a i7
:
> cpu.cpuILoad()
[ { cpu: 0,
idle: 148.75,
total: 1103.75,
percent: 0.8652321630804077 },
{ cpu: 1,
idle: 797.5,
total: 1103.75,
percent: 0.2774631936579841 },
{ cpu: 2,
idle: 142.5,
total: 1102.5,
percent: 0.8707482993197279 },
{ cpu: 3,
idle: 798.75,
total: 1102.5,
percent: 0.2755102040816326 },
{ cpu: 4,
idle: 146.25,
total: 1102.5,
percent: 0.8673469387755102 },
{ cpu: 5, idle: 795, total: 1102.5, percent: 0.2789115646258503 },
{ cpu: 6,
idle: 142.5,
total: 1102.5,
percent: 0.8707482993197279 },
{ cpu: 7,
idle: 796.25,
total: 1101.25,
percent: 0.27695800227014755 } ]
So this script seems to loop through all of the cores. Is it possible to shorten it in such a way that it only reads the first core? I'm running on a 1-core VPS, so I don't think there's any advantage for me to run through all cores.
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)
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.
Noob <, however how can i use this with chart.js?
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
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?
With love, but mine works better: https://gist.github.com/GaetanoPiazzolla/c40e1ebb9f709d091208e89baf9f4e00 <3
I rewrite it like closure function:
Usage: