gpt4 book ai didi

node.js - 如何使用 perf_hooks 来衡量异步操作?

转载 作者:行者123 更新时间:2023-12-03 12:15:47 33 4
gpt4 key购买 nike

这是描述由 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 测量异步操作?

最佳答案

看起来除了在 resolve 之后进行标记和测量之外别无他法。 .

const foo = async () => {
await new Promise((resolve) => {
performance.mark('A');

setTimeout(() => {
resolve();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
}, Math.random() * 100);
});

await new Promise((resolve) => {
performance.mark('C');
setTimeout(() => {
resolve();
performance.mark('D');
performance.measure('C to D', 'C', 'D');
}, 100);
});

performance.clearMarks();
};

Promise.all([
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
foo(),
]);

关于node.js - 如何使用 perf_hooks 来衡量异步操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261371/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com