Created
December 22, 2017 15:00
-
-
Save juliusza/05de666d7ab58db25520556836dda49e to your computer and use it in GitHub Desktop.
node.js event loop delay monitor (measures max CPU time spent processing ticks)
This file contains hidden or 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
const NS_PER_SEC = 1e9; | |
const NS_PER_MS = 1e6; | |
const SAMPLE_INTERVAL = 10; | |
class ProcessMonitor { | |
start(interval) { | |
let prevTime = [NaN, NaN]; | |
this.maxEventLoopDelay = 0; | |
if (!interval) { | |
interval = 5 * 1000; | |
} | |
this.samplerInterval = setInterval(() => { | |
const now = process.hrtime(); | |
const diff = [now[0] - prevTime[0], now[1] - prevTime[1]]; | |
if (!isNaN(diff[0])) { | |
const delay = ((diff[0] * NS_PER_SEC + diff[1]) / NS_PER_MS) - SAMPLE_INTERVAL; | |
if (delay > this.maxEventLoopDelay) { | |
this.maxEventLoopDelay = delay; | |
} | |
} | |
prevTime = now; | |
}, SAMPLE_INTERVAL); | |
this.monitorInterval = setInterval(() => { | |
// Feel free to add this to your stats backend | |
console.log(this.maxEventLoopDelay + " ms"); | |
this.maxEventLoopDelay = 0; | |
}, interval); | |
} | |
stop() { | |
clearTimeout(this.samplerInterval); | |
clearTimeout(this.monitorInterval); | |
} | |
} | |
module.exports = ProcessMonitor; | |
/* | |
This is fast, simple and no external dependencies | |
Usage: | |
const monitor = new ProcessMonitor(); | |
monitor.start(); | |
Outputs: | |
[2017-12-22 14:52:52] [LOG] [pid:10396] 16.39679 ms | |
[2017-12-22 14:52:57] [LOG] [pid:10396] 47.719075 ms | |
[2017-12-22 14:53:03] [LOG] [pid:10396] 1062.336003 ms <--- I simulate CPU load here | |
[2017-12-22 14:53:08] [LOG] [pid:10396] 823.406753 ms | |
[2017-12-22 14:53:13] [LOG] [pid:10396] 10.119005999999999 ms | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://www.npmjs.com/package/heavy
and https://www.npmjs.com/package/event-loop-monitor