Web Worker 中的 performance.now() 可靠吗?

Is performance.now() in web workers reliable?

我有这么长的 运行 脚本,由专门的网络工作者执行,我想知道执行需要多长时间,以现实世界的时间计算。

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

在此示例中,我希望 time2-time1 是 doSomethingSyncronous() 的实际持续时间,同样我希望 time3-time2 是 doSomethingAsyncrounous 的实际持续时间。

我认为工作线程可以在 CPU 想要的任何时候休眠,并且用 performance.now() 测量的持续时间是不正确的。这是一种正确的假设吗?在这种情况下,衡量网络工作者持续时间的正确方法是什么?

谢谢!

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?

部分。是的,OS 可以让线程随时休眠。这是在有更重要的工作要做时完成的,或者如果它决定节流 cpu 以节省电量(例如在移动设备上)。

但是不,这不会使持续时间测量不正确。这只是意味着您的代码在该特定环境中 运行 速度较慢。

听起来你是在问,如果工人实际上没有做某事,那么 performance.now() 测量的时间会增加吗?来自 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)

[强调我的]

所以它强烈建议时间一直在增加,而不仅仅是在工作人员做事的时候。

作为测试,您可以看到 http://plnkr.co/edit/alMahs56ACjzH10FUmus?p=preview 工作人员只是用 performance.now():

ping 回一条消息
self.onmessage = function() {
  self.postMessage(self.performance.now());
}

如果间隔1秒左右调用,每次会增加1秒左右,而工作线程实际计算的时间会少很多

因此,使用 performance.now() 来测量挂钟时间,包括工人何时做事和何时不做,似乎是完全合理的。