-
-
Save kolodny/ac7a135c2eaa0c52dfcf0a9e65eb826a to your computer and use it in GitHub Desktop.
get CPU usage percent for a process in node, using proposed `process.cpuUsage()` function
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
'use strict' | |
// see: https://github.com/nodejs/node/pull/6157 | |
var startTime = process.hrtime() | |
var startUsage = process.cpuUsage() | |
// spin the CPU for 500 milliseconds | |
var now = Date.now() | |
while (Date.now() - now < 500) | |
var elapTime = process.hrtime(startTime) | |
var elapUsage = process.cpuUsage(startUsage) | |
var elapTimeMS = secNSec2ms(elapTime) | |
var elapUserMS = secNSec2ms(elapUsage.user) | |
var elapSystMS = secNSec2ms(elapUsage.system) | |
var cpuPercent = Math.round(100 * (elapUserMS + elapSystMS) / elapTimeMS) | |
console.log('elapsed time ms: ', elapTimeMS) | |
console.log('elapsed user ms: ', elapUserMS) | |
console.log('elapsed system ms:', elapSystMS) | |
console.log('cpu percent: ', cpuPercent) | |
function secNSec2ms (secNSec) { | |
return secNSec[0] * 1000 + secNSec[1] / 1000000 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment