下面是一个代码段,描述了foo
方法执行的两个异步操作:
const foo = async () => {
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, Math.random() * 100);
});
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 100);
});
};
Promise.all([
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo()
])
我希望测量每个异步操作需要多长时间,然后每个foo
执行总共需要多长时间。
我的第一次尝试是:
const { PerformanceObserver, performance } = require('perf_hooks');
const obs = new PerformanceObserver((items) => {
console.log('performance-observer', items.getEntries());
});
obs.observe({
entryTypes: ['measure']
});
const foo = async () => {
performance.mark('A');
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, Math.random() * 100);
});
performance.mark('B');
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 100);
});
performance.mark('C');
performance.measure('A to B', 'A', 'B');
performance.measure('A to C', 'A', 'C');
performance.measure('B to C', 'B', 'C');
performance.clearMarks();
};
Promise.all([
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo()
]);
然而,这个操作(顾名思义)会抛出一个错误:
(node:29277) UnhandledPromiseRejectionWarning: Error [ERR_INVALID_PERFORMANCE_MARK]: The "B" performance mark has not been set
at Performance.measure (perf_hooks.js:396:13)
at foo (/Users/gajus/Documents/dev/temp/test.js:30:15)
at async Promise.all (index 0)
这是因为PerformanceObserver
实例和单个性能标记之间没有关联。
如何使用perf_hooks
来测量异步操作?