Last active
August 29, 2015 13:56
-
-
Save arunoda/8897526 to your computer and use it in GitHub Desktop.
Lookup CPU usage in details
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
/* | |
USAGE: node cpu-watch.js <pid> <how-many-minutes> | |
*/ | |
var fs = require('fs'); | |
var format = require('util').format; | |
var PID = process.env.PID || process.argv[2]; | |
if(!PID) throw new Error('No PIC Provided!'); | |
var ENDIN_MINUTES = process.env.ENDIN_MINUTES || process.argv[3]; | |
var INTERVAL_MILLIES = 2000; | |
var startedAt = Date.now(); | |
var startedTimes; | |
var previous = {}; | |
processTimes(); | |
var processTimesInterval = setInterval(processTimes, INTERVAL_MILLIES); | |
process.on('SIGINT', atTheEnd); | |
if(ENDIN_MINUTES) { | |
setTimeout(atTheEnd, ENDIN_MINUTES * 1000 * 60); | |
} | |
function processTimes(processTimes) { | |
var times = getTimes(); | |
if(!startedTimes) startedTimes = times; | |
if(previous.times) { | |
var sectionTimes = getSectionTimes(times, previous.times, INTERVAL_MILLIES); | |
console.log('%s + %s = %s (%s%)', | |
sectionTimes.stime, sectionTimes.utime, sectionTimes.total, sectionTimes.ptotal); | |
previous.sectionTimes = sectionTimes; | |
} | |
previous.times = times; | |
} | |
function getSectionTimes(currTimes, previousTimes, elaspedMillis) { | |
var sectionTimes = {}; | |
sectionTimes.utime = currTimes.utime - previousTimes.utime; | |
sectionTimes.stime = currTimes.stime - previousTimes.stime; | |
sectionTimes.total = sectionTimes.utime + sectionTimes.stime; | |
sectionTimes.ptotal = ((sectionTimes.total * 1000/100) / elaspedMillis) * 100; | |
sectionTimes.ptotal = sectionTimes.ptotal.toFixed(2); | |
return sectionTimes; | |
} | |
function atTheEnd() { | |
var times = getTimes(); | |
var elaspedMillis = Date.now() - startedAt; | |
var elaspedSecs = (elaspedMillis/1000).toFixed(2); | |
var sectionTimes = getSectionTimes(times, startedTimes, elaspedMillis); | |
console.log('\nAVG(%ssec) => %s + %s = %s (%s%)', elaspedSecs, | |
sectionTimes.stime, sectionTimes.utime, sectionTimes.total, sectionTimes.ptotal); | |
process.exit(0); | |
} | |
function getTimes() { | |
var content = fs.readFileSync(format('/proc/%s/stat', PID), 'utf8'); | |
content = content.substr(content.lastIndexOf(')') + 2); | |
var parts = content.split(' '); | |
return { | |
stime: parts[12], | |
utime: parts[11] | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment