gpt4 book ai didi

io - 为什么 read_line(..) 比 lines() 慢得多?

转载 作者:行者123 更新时间:2023-11-29 08:10:11 26 4
gpt4 key购买 nike

下面的代码在调用 read_line(..) 时比 lines() 运行得慢得多你不能在 Playground 上运行它,但对我来说,它会打印以下内容

lines()     took Duration { secs: 0, nanos: 41660031 }
read_line() took Duration { secs: 2, nanos: 379397138 }

implementation of Lines几乎和我写的一样(但更多!)为什么会有这样的不同?

use std::net::{TcpListener, TcpStream};
use std::io::{BufRead, BufReader, Write};
use std::thread;

fn main() {

let listener = TcpListener::bind("127.0.0.1:80")
.expect("listen failed");
thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
thread::spawn(move || {
for x in 1..1000 + 1 {
stream.write_all(format!("{}\n", x).as_bytes())
.expect("write failed");
}
});
}
});

let start_a = std::time::Instant::now();
{
let stream_a = TcpStream::connect("127.0.0.1:80")
.expect("connect_a failed");
let br = BufReader::new(stream_a);
for l in br.lines() {
println!("{}", l.unwrap());
}
}
let end_a = std::time::Instant::now();

let start_b = std::time::Instant::now();
{
let stream_b = TcpStream::connect("127.0.0.1:80")
.expect("connect_b failed");
let mut br = BufReader::new(stream_b);
let mut s = String::with_capacity(10);
while br.read_line(&mut s).unwrap_or(0) > 0 {
println!("{}", s);
}
}
let end_b = std::time::Instant::now();

let dur_a = end_a - start_a;
let dur_b = end_b - start_b;

println!("lines() took {:?}", dur_a);
println!("read_line() took {:?}", dur_b);

}

same code on the playground

最佳答案

让我们看一下程序的输出:

1 
2
...
999
1000
1

1
2

1
2
3

1
2
3
4

1
2
3
4
5

...

糟糕。这只是代码中的一个简单错误:您永远不会clear() 字符串。每个 read_line() 调用都会附加到您的字符串。当我在您的 while 循环中添加一个 s.clear() 时,时间安排更具可比性:

lines()     took Duration { secs: 0, nanos: 7323617 }
read_line() took Duration { secs: 0, nanos: 2877078 }

在您的错误程序中,大部分时间可能浪费在重新分配字符串并将其打印到终端上。

关于io - 为什么 read_line(..) 比 lines() 慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220448/

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