asynchronous - How to calculate the execution time of an async function in JavaScript? -


i calculate how long async function (async/await) taking in javascript.

one do:

const asyncfunc = async function () {};  const before = date.now(); asyncfunc().then(() => {   const after = date.now();   console.log(after - before); }); 

however, not work, because promises callbacks run in new microtask. i.e. between end of asyncfunc() , beginning of then(() => {}), queued microtask fired first, , execution time taken account.

e.g.:

const asyncfunc = async function () {};  const slowsyncfunc = function () {   (let = 1; < 10 ** 9; i++) {} };  process.nexttick(slowsyncfunc);  const before = date.now(); asyncfunc().then(() => {   const after = date.now();   console.log(after - before); }); 

this prints 1739 on machine, i.e. 2 seconds, because waits slowsyncfunc() complete, wrong.

note not want modify body of asyncfunc, need instrument many async functions without burden of modifying each of them. otherwise add date.now() statement @ beginning , end of asyncfunc.

note problem not how performance counter being retrieved. using date.now(), console.time(), process.hrtime() (node.js only) or performance (browser only) not change base of problem. problem fact promise callbacks run in new microtask. if add statements settimeout or process.nexttick original example, modifying problem.

any queued microtask fired first, , execution time taken account.

yes, , there's no way around that. if don't want have other tasks contribute measurement, don't queue any. that's solution.

this not problem of promises (or async functions) or of microtask queue specifically, it's problem shared all asynchronous things run callbacks on task queue.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -