Event loop monitoring — detect event loop lag.
1class EventLoopMonitor {2 constructor(options = {}) {3 this.interval = options.interval || 1000;4 this.lags = [];5 this.timer = null;6 }78 start() {9 let lastCheck = process.hrtime.bigint();1011 this.timer = setInterval(() => {12 const now = process.hrtime.bigint();13 const expected = BigInt(this.interval) * 1000000n;14 const actual = now - lastCheck;15 const lag = Number(actual - expected) / 1000000; // ms1617 this.lags.push({18 timestamp: Date.now(),19 lag,20 });2122 if (this.lags.length > 300) this.lags.shift();2324 if (lag > 100) {25 console.warn(`Event loop lag: ${lag.toFixed(2)}ms`);26 }2728 lastCheck = now;29 }, this.interval);30 }3132 stop() {33 clearInterval(this.timer);34 }3536 getStats() {37 if (this.lags.length === 0) return null;38 const lags = this.lags.map(l => l.lag);39 lags.sort((a, b) => a - b);4041 return {42 avg: lags.reduce((a, b) => a + b, 0) / lags.length,43 min: lags[0],44 max: lags[lags.length - 1],45 p95: lags[Math.floor(lags.length * 0.95)],46 p99: lags[Math.floor(lags.length * 0.99)],47 };48 }49}5051const monitor = new EventLoopMonitor();52monitor.start();5354setInterval(() => {55 console.log("Event loop stats:", monitor.getStats());56}, 30000);