performance.eventLoopUtilization([utilization1[, utilization2]])
utilization1
<Object> 上一次调用eventLoopUtilization()
的结果。utilization2
<Object> 在utilization1
之前调用eventLoopUtilization()
的结果。- 返回 <Object>
与 perf_hooks
eventLoopUtilization()
相同的调用,除了返回工作线程实例的值。
一个区别是,与主线程不同,工作线程内的引导是在事件循环内完成的。 因此,一旦工作线程的脚本开始执行,则事件循环利用率将立即可用。
不增加的 idle
时间并不表示工作线程卡在引导中。
下面的示例展示了工作线程的整个生命周期永远不会累积任何 idle
时间,但仍然能够处理消息。
const { Worker, isMainThread, parentPort } = require('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 toeventLoopUtilization()
.utilization2
<Object> The result of a previous call toeventLoopUtilization()
prior toutilization1
.- 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 will be 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 will never accumulate any idle
time, but is still be able to process
messages.
const { Worker, isMainThread, parentPort } = require('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
.