perf_hooks.monitorEventLoopDelay([options])


  • options <Object>
    • samplePerIteration <boolean> 当 true 时,每次事件循环迭代都会采样一次。默认值: false。
    • resolution <number> 用于基于间隔采样的采样率(毫秒)。必须大于零。当 samplePerIteration 为 true 时,此选项将被忽略。默认值: 10。
    • lowest <number> | <bigint> 可察觉的最小延迟,单位为纳秒。必须是大于 0 的整数值。默认值: 当 samplePerIteration 为 true 时为 1,否则为 1000。
    • highest <number> | <bigint> 可记录的最高延迟,单位为纳秒。必须是一个整数,且大于或等于 lowest 的两倍。默认值: 2n ** 63n - 1n。
    • figures <number> 精确位数。必须是介于 1 和 5 之间的整数。默认值: 3。
  • 返回:ELDHistogram

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

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

创建一个直方图对象,用来采样并报告事件循环随时间的延迟。这些延迟将以纳秒为单位报告。

🌐 Creates a histogram object that samples and reports the event loop delay over time. The delays will be reported in nanoseconds.

默认情况下,直方图会通过使用配置好的resolution的定时器来更新。当samplePerIteration为true时,会使用uv_prepare_t和uv_check_t钩子在每次事件循环迭代中采样。在这种模式下,直方图不会保持循环运行,也不会在应用空闲时强制进行额外的迭代。这两种采样模式产生的结果差异很大,不应直接比较。

🌐 By default, the histogram is updated by a timer using the configured resolution. When samplePerIteration is true, samples are taken once per event loop iteration using uv_prepare_t and uv_check_t hooks. In that mode, the histogram does not keep the loop alive or force additional iterations when the application is idle. The two sampling modes produce significantly different results and should not be compared directly.

lowest、highest 和 figures 选项的配置方式和 perf_hooks.createHistogram() 一样。lowest 必须大于 0,因为事件循环延迟为零是不可能的:事件循环有最小开销,而且测量本身依赖于事件循环的运行。大于 highest 的延迟不会被记录,而是由 histogram.exceeds 来计数。使用基于间隔的采样时,每个样本都包含 resolution,所以 highest 应该比 resolution * 1e6 高很多。直方图的内存使用取决于这些选项,而不是样本数量。

🌐 The lowest, highest, and figures options configure the histogram as they do for perf_hooks.createHistogram(). lowest must be greater than 0 because an event loop delay of zero is not possible: the event loop has a minimal overhead, and the measurement itself depends on the event loop turning. Delays greater than highest are not recorded, and are counted by histogram.exceeds instead. With interval-based sampling, every sample includes the resolution, so highest should be well above resolution * 1e6. The histogram's memory use depends on these options, not on the number of samples.

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