performance.eventLoopUtilization([utilization1[, utilization2]])


perf_hooks eventLoopUtilization() 相同的调用,除了返回工作线程实例的值。

一个区别是,与主线程不同,工作线程内的引导是在事件循环内完成的。 因此,一旦工作线程的脚本开始执行,事件循环的利用率将立即可用。

不增加的 idle 时间并不表示工作线程卡在引导中。 下面的示例展示了工作线程的整个生命周期从未累积任何 idle 时间,但仍然能够处理消息。

const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  setInterval(() => {
    worker.postMessage('hi');
    console.log(worker.performance.eventLoopUtilization());
  }, 100).unref();
  return;
}

parentPort.on('message', () => console.log('msg')).unref();
(function r(n) {
  if (--n < 0) return;
  const t = Date.now();
  while (Date.now() - t < 300);
  setImmediate(r, n);
})(10);

工作线程的事件循环利用率仅在 'online' 事件触发后可用,如果在此之前或在 'exit' 事件之后调用,则所有属性的值都为 0

  • utilization1 <Object> The result of a previous call to eventLoopUtilization().
  • utilization2 <Object> The result of a previous call to eventLoopUtilization() prior to utilization1.
  • Returns <Object>

The same call as perf_hooks eventLoopUtilization(), except the values of the worker instance are returned.

One difference is that, unlike the main thread, bootstrapping within a worker is done within the event loop. So the event loop utilization is immediately available once the worker's script begins execution.

An idle time that does not increase does not indicate that the worker is stuck in bootstrap. The following examples shows how the worker's entire lifetime never accumulates any idle time, but is still be able to process messages.

const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  setInterval(() => {
    worker.postMessage('hi');
    console.log(worker.performance.eventLoopUtilization());
  }, 100).unref();
  return;
}

parentPort.on('message', () => console.log('msg')).unref();
(function r(n) {
  if (--n < 0) return;
  const t = Date.now();
  while (Date.now() - t < 300);
  setImmediate(r, n);
})(10);

The event loop utilization of a worker is available only after the 'online' event emitted, and if called before this, or after the 'exit' event, then all properties have the value of 0.