Performance.now() in a multi threaded context

275 Views Asked by At

I need to use web workers for a demanding computation. I have const t0 = performance.now() and const t1 = performance.now() respectively at the beginning and the end of my code. I want to report t1 - t0 as the time required to perform the computation. But if the web worker is actually running in another thread, does it mean that it can be interrupted by some scheduler ? If yes, then it means that t1 - t0 could be greater than the actual computation time (like this: timeline)... How would you measure execution time in a multi threaded context, in javascript ? Thanks in advance to anyone willing to help me understand.

1

There are 1 best solutions below

4
Kaiido On

The DOMHighResTimeStamp API uses global monotonic clocks which should never be paused or even throttled.

In certain scenarios (e.g. when a tab is backgrounded), the user agent may choose to throttle timers and periodic callbacks run in that context or even freeze them entirely. Any such throttling should not affect the resolution or accuracy of the time returned by the monotonic clock.

So you can be confident that performance.now() will return the correct time since the Worker was created, as long as the browser itself is still running. Indeed, for instance if the computer is set to sleep, then the clocks won't tick anymore.