gpt4 book ai didi

javascript - Node js,为什么50ms的setTimeout比setTimeout 0快

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

我已经是 Node.js 开发人员一年了。昨晚我想我会在 express 和 http 模块之间做一个基准测试,基本上它是一个简单的 promise,它返回一个字符串并将它传递给响应,现在我看到 http 更快,但我遇到了一个不同的问题, 如果我在 ab 测试中将 setTimeout 设置为 50 ms,并发 500 和 100000 个请求,响应时间比 setTimeout 0 或 process 快两倍.nextTick

现在我知道 setTimeout 将它带到下一个周期,但在队列的末尾, nextTick 将它放在下一个周期的首位,但我真的不理解为什么 setTimeout 50ms 比 setTimeout 0 快。即使没有 setTimeout,ab 测试也比 setTimeout 50ms 慢很多。

我怀疑它与 apache ab 测试有关,或者我错过了 Node 的某些东西?

http.createServer((req,res)=>{
setTimeout(()=>{
check().then(data=>{
res.write(data);
res.end();
})
},0)

}).listen(3000);

let check = () =>{
return Promise.try(()=>{
return 'done with Async'
})
};

// setTimeout 0 times with ab test
Concurrency Level: 500
Time taken for tests: 53.824 seconds
Complete requests: 100000
Failed requests: 0
Total transferred: 9000000 bytes
HTML transferred: 1500000 bytes
Requests per second: 1857.90 [#/sec] (mean)
Time per request: 269.121 [ms] (mean)
Time per request: 0.538 [ms] (mean, across all concurrent requests)
Transfer rate: 163.29 [Kbytes/sec] received

// setTimeout 50ms response times
Concurrency Level: 500
Time taken for tests: 23.174 seconds
Complete requests: 100000
Failed requests: 0
Total transferred: 9000000 bytes
HTML transferred: 1500000 bytes
Requests per second: 4315.12 [#/sec] (mean)
Time per request: 115.872 [ms] (mean)
Time per request: 0.232 [ms] (mean, across all concurrent requests)
Transfer rate: 379.26 [Kbytes/sec] received

最佳答案

当您使用 setTimeout(0) 时,您在进程中添加了一个额外的作业,这可能需要一些时间。但是使用 setTimeout(50),请求会在队列中准备好,并且在 50 毫秒后,它们将被完全发送出去,而不需要额外的时间。例如,考虑一个请求需要 10 毫秒发送和 10 毫秒获得响应。通过使用 setTimeout(50),发送 500 个请求将花费 5000ms 加上 50ms 超时和 10ms 响应,它将花费 5060ms。现在,如果我们使用 setTimeout(0),我们将有 10ms 用于发送请求,10ms 用于获取响应。因此,对于 500 个请求,它将花费 10000 毫秒。

关于javascript - Node js,为什么50ms的setTimeout比setTimeout 0快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666855/

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