Last active
December 18, 2015 05:38
-
-
Save marcelduran/5733644 to your computer and use it in GitHub Desktop.
Getting CPU(s) usage % with NodeJS,based on: https://github.com/oscmejia/os-utils/blob/master/lib/osutils.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var os = require('os'); | |
const RESOLUTION = 1000; // 1s CPU resolution | |
function cpusInfo() { | |
return os.cpus().map(function(cpu) { | |
var t = cpu.times; | |
return { | |
total: t.user + t.nice + t.sys + t.irq + t.idle, | |
idle: t.idle | |
}; | |
}); | |
} | |
function cpuInfo() { | |
return cpusInfo().reduce(function(previous, cpu) { | |
return { | |
total: previous.total += cpu.total, | |
idle: previous.idle += cpu.idle | |
}; | |
}, { | |
total: 0, | |
idle: 0 | |
}); | |
} | |
function cpusUsage(callback) { | |
setTimeout(function(begin) { | |
callback(cpusInfo().map(function(cpu, index) { | |
var cpuBegin = begin[index]; | |
return 1 - (cpu.idle - cpuBegin.idle) / (cpu.total - cpuBegin.total); | |
})); | |
}, RESOLUTION, cpusInfo()); | |
} | |
function cpuUsage(callback) { | |
setTimeout(function(begin) { | |
var end = cpuInfo(); | |
callback(1 - (end.idle - begin.idle) / (end.total - begin.total)); | |
}, RESOLUTION, cpuInfo()); | |
} | |
// Individual cores usage. | |
// setInterval(cpusUsage.bind(null, console.log), 1000); | |
// Combined cores usage. | |
setInterval(cpuUsage.bind(null, console.log), 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment