Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Io 为什么read_line(..)比line()慢得多?_Io_Rust - Fatal编程技术网

Io 为什么read_line(..)比line()慢得多?

Io 为什么read_line(..)比line()慢得多?,io,rust,Io,Rust,调用read\u-line(..)时,下面的代码比line()运行得慢得多。 你不能在操场上跑步,但对我来说,这打印了以下内容 lines()花费了持续时间{secs:0,nanos:41660031} read_line()花费了持续时间{secs:2,nanos:379397138} 我写的东西基本上都是一样的(但更多!)为什么会有这样的区别 use std::net::{TcpListener, TcpStream}; use std::io::{BufRead, BufReader,

调用
read\u-line(..)
时,下面的代码比
line()运行得慢得多。
你不能在操场上跑步,但对我来说,这打印了以下内容

lines()花费了持续时间{secs:0,nanos:41660031}
read_line()花费了持续时间{secs:2,nanos:379397138}
我写的东西基本上都是一样的(但更多!)为什么会有这样的区别

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);

}

让我们看看程序的输出:

1
2.
...
999
1000
1.
1.
2.
1.
2.
3.
1.
2.
3.
4.
1.
2.
3.
4.
5.
...
哎呀。这只是代码中的一个简单错误:您从未
clear()
string。每个
read\u line()
调用都会附加到字符串中。当我在
while
循环中添加
s.clear()
时,计时更具可比性:

lines()花费了持续时间{secs:0,nanos:7323617}
read_line()花费了持续时间{secs:0,nanos:2877078}

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

您是否使用
--release
标志进行了测试?每当有人说锈代码“不够快”时,这就是第一个问题。天才!感谢长达15年的编程,这也吸引了我。感觉这个错误应该比现在更难犯。