gpt4 book ai didi

rust - 在 `loop` 中使用 Rust 的错误会导致廉价的阻塞,但为什么呢?

转载 作者:行者123 更新时间:2023-11-29 07:48:54 25 4
gpt4 key购买 nike

use std::io::ErrorKind;
use std::net::TcpStream;

fn main() {
let address = "localhost:7000";

loop {
match TcpStream::connect(address.clone()) {
Err(err) => { match err.kind() {
ErrorKind::ConnectionRefused => { continue; },
kind => panic!("Error occurred: {:?}", kind),
}; },
Ok(_stream) => { /* do some stuff here */ },
}
}
}

考虑上面的一段 Rust 代码。我感兴趣的不是 Ok 分支,而是 ErrorKind::ConnectionRefused 子分支加上 loop:它非常便宜, CPU-wise, 消耗不到 1% CPU.这太棒了,这就是我想要的。

但我不明白为什么它很便宜:C 中的可比较代码可能会消耗 100% 基本上 NOPing(不精确但足够接近)。谁能帮我理解为什么这么便宜?

最佳答案

很可能 connect() 是罪魁祸首;为了收到Connection refused 错误,它首先需要查找地址(对于本地主机来说应该很便宜),然后连接,并等待Connection refused 响应.

虽然 localhost 相对于远程网络服务肯定是相当快的,但仍然有很多开销。

ping localhost 对我来说有大约 0.9 毫秒的延迟。这意味着您的循环每秒仅进行大约 1000 到 10000 次迭代,与实际的 while true {} 循环相比并不算多。

关于rust - 在 `loop` 中使用 Rust 的错误会导致廉价的阻塞,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37635087/

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