performance.eventLoopUtilization([utilization1[, utilization2]])
utilization1<Object> 前一次调用eventLoopUtilization()的结果。utilization2<Object> 在utilization1之前对eventLoopUtilization()的先前调用的结果。- 返回:<Object>
与 perf_hooks eventLoopUtilization() 相同的调用,只是返回了 worker 实例的值。
【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.】
一个不增加的 idle 时间并不意味着工作线程卡在了引导阶段。下面的示例展示了工作线程在整个生命周期中从未积累任何 idle 时间,但仍然能够处理消息。
【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.】
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
setInterval(() => {
worker.postMessage('hi');
console.log(worker.performance.eventLoopUtilization());
}, 100).unref();
} else {
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);
}'use strict';
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();
} else {
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);
}只有在 '在线'事件 发出之后,才能获取工作线程的事件循环利用率,如果在此之前或在 'exit'事件 之后调用,则所有属性的值都为 0。
【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.】