javascriptmultithreadingasynchronousweb-workerperformance.now

Is performance.now() in web workers reliable?


I have this long running script that is being executed by a dedicated web worker, and I want to know how long time the execution takes, in real world time.

time1 = performance.now();   
doSomethingSyncronous();
time2 = performance.now();
doSomethingAsyncronous(function() {
   time3 = performance.now();
}
doSomethingSyncrounous();
time4 = performance.now();

In this example I want time2-time1 to be the actual duration of doSomethingSyncronous(), in the same way I want time3-time2 to be the actual duration of doSomethingAsyncrounous.

I would like to think that the worker threads can sleep whenever the CPU wants to, and the duration measured with performance.now() would be incorrect. Is that a kind of correct assumption? In that case, what would be the correct way of measuring duration in web workers?

Thanks!


Solution

  • It sounds like you're asking that if the worker isn't actually doing something, then does time measured by performance.now() increase? From https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

    the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP)

    [emphasis mine]

    So it strongly suggests the time increases at all times, not just when the worker is doing things.

    As a test, you can see http://plnkr.co/edit/alMahs56ACjzH10FUmus?p=preview where the worker just pings back a message with performance.now():

    self.onmessage = function() {
      self.postMessage(self.performance.now());
    }
    

    If called with an interval of about 1 second, the time goes up by about 1 second each time, while the time in actual computation of the worker thread is much less.

    So using performance.now() to measure wallclock time, that includes when the worker is doing things and when it isn't, seems perfectly reasonable.