Created
April 12, 2016 14:59
-
-
Save pmuellr/8c349726392bb47da680410eb7904092 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 | |
} |
The workable codes for node v12.x
:
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) {
if (Array.isArray(secNSec)) {
return secNSec[0] * 1000 + secNSec[1] / 1000000;
}
return secNSec / 1000;
}
Thank you @aprilandjan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, it is giving the wrong output. Try changing function secNsec2ms...
function secNSec2ms(secNSec) { if (Array.isArray(secNSec)) return secNSec[0] * 1000 + secNSec[1] / 1000000 return secNSec / 1000; }