gpt4 book ai didi

node.js - 为什么 node.js 处理 setTimeout(func, 1.0) 不正确?

转载 作者:IT老高 更新时间:2023-10-28 23:26:28 26 4
gpt4 key购买 nike

在处理对时间敏感的项目时,我使用下面的代码来测试可用的时间事件的粒度,首先在我的桌面计算机上使用 Firefox,然后在我的 Linux 服务器上作为 node.js 代码。 Firefox 运行产生了可预测的结果,在 1 毫秒超时时平均 200 fps,并表明我有 5 毫秒粒度的计时事件。

现在我知道,如果我使用 0 的超时值,则构建 Node.js 的 Chrome V8 引擎实际上不会将超时委托(delegate)给事件,而是立即处理它。正如预期的那样,这些数字平均为 60,000 fps,显然是在 CPU 容量下不断处理(并通过 top 验证)。但是在 1 毫秒超时的情况下,数字仍然在每秒 3.5-4 千次循环()左右,这意味着 Node.js 不可能遵守 1 毫秒超时,这将产生理论上每秒 1 千次循环()的最大值。

玩一系列数字,我得到:

  • 2ms:~100 fps(真正的超时,表示 Linux 上 10ms 的计时事件粒度)
  • 1.5:相同
  • 1.0001:相同
  • 1.0:3,500 - 4,500 帧/秒
  • 0.99:2,800 - 3,600 帧/秒
  • 0.5:1,100 - 2,800 帧/秒
  • 0.0001:1,800 - 3,300 帧/秒
  • 0.0:~60,000 帧/秒

setTimeout(func, 0) 的行为似乎是可以原谅的,因为 ECMAScript 规范大概没有 promise setTimout 将调用委托(delegate)给实际的操作系统级中断。但是任何 0 < x <= 1.0 的结果显然是荒谬的。我给出了一个明确的延迟时间,在 x 延迟上 n 次调用的理论最短时间应该是 (n-1)*x。 V8/Node.js 到底在做什么?

var timer, counter = 0, time = new Date().getTime();

function cycle() {
counter++;
var curT = new Date().getTime();
if(curT - time > 1000) {
console.log(counter+" fps");
time += 1000;
counter = 0;
}
timer = setTimeout(cycle, 1);
}

function stop() {
clearTimeout(timer);
}

setTimeout(stop, 10000);
cycle();

最佳答案

来自 node.js api docs for setTimeout(cb, ms) (强调我的):

It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

我认为“尽可能接近”对实现团队的意义与对您不同。

[编辑] 顺便说一下,setTimeout() function任何规范都没有强制要求(尽管 apparently part of the HTML5 draft )。此外,实际上似乎有 4-10 毫秒的最小粒度级别,所以这似乎是“它就是这样”。

开源软件的伟大之处在于,您可以根据自己的需要贡献一个补丁来包含更高的分辨率!

关于node.js - 为什么 node.js 处理 setTimeout(func, 1.0) 不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9288050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com