Skip to content

Instantly share code, notes, and snippets.

@cmargroff
Created August 6, 2018 19:51
Show Gist options
  • Save cmargroff/f5fa30b179b42f1bebd605838e332b8a to your computer and use it in GitHub Desktop.
Save cmargroff/f5fa30b179b42f1bebd605838e332b8a to your computer and use it in GitHub Desktop.
emulates loadavg for windows platforms
var lastCpus = [];
var lastTimestamp = 0;
const { performance } = require('perf_hooks');
function AvgList(limit){
this.measures = [];
this.totalTime = 0;
this.limit = limit;
this.push = function(measure){
if ((this.totalTime + measure.delta) > this.limit) {
console.log("samples exceed limit");
var delta = measure.delta;
this.measures = this.measures.filter((filtermeasure) => {
if (delta > 0) {
delta -= filtermeasure.delta;
this.totalTime -= filtermeasure.delta;
return false;
}else{
return true;
}
});
}
this.measures.push(measure);
}
this.getAvg = function(period){
if (!period) {
period = this.limit;
}
var count = 0;
var total = 0;
var totalTime = 0;
for (var i = this.measures.length - 1; i >= 0; i--) {
var measure = this.measures[i];
if ((totalTime + measure.delta) < period) {
count++;
total += measure.avg;
totalTime += measure.delta;
}else{
var scale = (period-totalTime) / measure.delta;
count += scale;
total += measure.avg*scale;
totalTime += measure.delta*scale;
break;
}
}
return total/count;
}
}
var avglist = new AvgList(10*60*1000);/*hold up to 10 minutes of data*/
function cpuAvg(cpus){
var avg = 0;
for (var i = 0; i < cpus.length; i++) {
var deltaTimes = {
total: 0
};
for (key in cpus[i].times) {
deltaTimes[key] = cpus[i].times[key] - lastCpus[i].times[key];
deltaTimes.total += deltaTimes[key];
}
if (deltaTimes.total>0) {
avg += (deltaTimes.total - deltaTimes.idle) / deltaTimes.total;
}
}
return avg;
}
function loadavg(){
var cpus = this.cpus();
var avg = cpuAvg(cpus);
lastCpus = cpus;
var now = performance.now();
avglist.push({avg: avg, delta: now-lastTimestamp});
lastTimestamp = now;
return [parseFloat(avglist.getAvg(60*1000).toFixed(2)), parseFloat(avglist.getAvg(5*60*1000).toFixed(2)), parseFloat(avglist.getAvg().toFixed(2))]
}
function bind(os){
os.loadavg = loadavg;
lastCpus = os.cpus();
lastTimestamp = performance.now();
}
module.exports = bind;
@cmargroff
Copy link
Author

cmargroff commented Aug 6, 2018

example

var os = require('os');
if (os.platform() == "win32") {
  require('./windows-loadavg.js')(os);
}
console.log(os.loadavg());

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