如何计算JavaScript中异步函数的执行时间? [英] How to calculate the execution time of an async function in JavaScript?

查看:106
本文介绍了如何计算JavaScript中异步函数的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算异步功能( async / await )在JavaScript中花费的时间.

I would like to calculate how long an async function (async/await) is taking in JavaScript.

一个人可以做:

const asyncFunc = async function () {};

const before = Date.now();
asyncFunc().then(() => {
  const after = Date.now();
  console.log(after - before);
});

但是,这不起作用,因为promise回调在新的微任务中运行.IE.在 asyncFunc()的末尾与 then(()=> {})的开始之间,将首先触发任何已排队的微任务,其执行时间将被考虑在内.

However, this does not work, because promises callbacks are run in a new microtask. I.e. between the end of asyncFunc() and the beginning of then(() => {}), any already queued microtask will be fired first, and their execution time will be taken into account.

例如:

const asyncFunc = async function () {};

const slowSyncFunc = function () {
  for (let i = 1; i < 10 ** 9; i++) {}
};

process.nextTick(slowSyncFunc);

const before = Date.now();
asyncFunc().then(() => {
  const after = Date.now();
  console.log(after - before);
});

这会在我的机器上打印 1739 ,即将近2秒钟,因为它等待 slowSyncFunc()完成,这是错误的.

This prints 1739 on my machine, i.e. almost 2 seconds, because it waits for slowSyncFunc() to complete, which is wrong.

请注意,我不想修改 asyncFunc 的主体,因为我需要检测许多异步函数,而无需承担修改每个异步函数的负担.否则,我可以在 asyncFunc 的开头和结尾处添加 Date.now()语句.

Note that I do not want to modify the body of asyncFunc, as I need to instrument many async functions without the burden of modifying each of them. Otherwise I could just add a Date.now() statement at the beginning and the end of asyncFunc.

还请注意,问题不在于如何检索性能计数器.使用 Date.now() console.time() process.hrtime()(仅Node.js)或 performance(仅限浏览器)不会更改此问题的基础.问题是关于答应回调在新的微任务中运行的事实.如果在原始示例中添加诸如 setTimeout process.nextTick 之类的语句,则您正在修改问题.

Note also that the problem is not about how the performance counter is being retrieved. Using Date.now(), console.time(), process.hrtime() (Node.js only) or performance (browser only) will not change the base of this problem. The problem is about the fact that promise callbacks are run in a new microtask. If you add statements like setTimeout or process.nextTick to the original example, you are modifying the problem.

推荐答案

任何已经排队的微任务都将首先被触发,并且将考虑它们的执行时间.

Any already queued microtask will be fired first, and their execution time will be taken into account.

是的,没有办法解决.如果您不想让其他任务参与您的测量,请不要排队.那是唯一的解决方案.

Yes, and there's no way around that. If you don't want to have other tasks contribute to your measurement, don't queue any. That's the only solution.

这不是promise(或异步函数 s)或微任务队列的问题,这是所有异步事物共享的一个问题,所有异步事物都在任务队列.

This is not a problem of promises (or async functions) or of the microtask queue specifically, it's a problem shared by all asynchronous things which run callbacks on a task queue.

这篇关于如何计算JavaScript中异步函数的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆