Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
@abhi11210646

This comment has been minimized.

Copy link

@abhi11210646 abhi11210646 commented Jan 10, 2020

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; }

@aprilandjan

This comment has been minimized.

Copy link

@aprilandjan aprilandjan commented Oct 13, 2020

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; 
}
@theironcook

This comment has been minimized.

Copy link

@theironcook theironcook commented Oct 26, 2020

Thank you @aprilandjan

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