perf_hooks.monitorEventLoopDelay([options])


此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。

¥This property is an extension by Node.js. It is not available in Web browsers.

创建可随时间采样并报告事件循环延迟的 IntervalHistogram 对象。延迟将以纳秒为单位报告。

¥Creates an IntervalHistogram object that samples and reports the event loop delay over time. The delays will be reported in nanoseconds.

使用定时器来检测近似的事件循环延迟是有效的,因为定时器的执行与 libuv 事件循环的生命周期特别相关。也就是说,循环中的延迟会导致定时器执行的延迟,而这些延迟正是此 API 旨在检测的。

¥Using a timer to detect approximate event loop delay works because the execution of timers is tied specifically to the lifecycle of the libuv event loop. That is, a delay in the loop will cause a delay in the execution of the timer, and those delays are specifically what this API is intended to detect.

import { monitorEventLoopDelay } from 'node:perf_hooks';

const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));const { monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));