Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Created April 12, 2016 14:59
Show Gist options
  • Save pmuellr/8c349726392bb47da680410eb7904092 to your computer and use it in GitHub Desktop.
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
'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
}
@theironcook
Copy link

Thank you @aprilandjan

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