2017-07-20 61 views
0

調用read_line(..)lines() 你不能運行在操場上,但對我來說這將打印以下爲什麼read_line(..)比lines()慢得多?

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

+2

**您是否使用'--release'標誌**進行測試?當有人說Rust代碼不夠「足夠快」時,這就是頭號問題。 – Shepmaster

回答

8

讓我們來看看你的程序的輸出:

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 } 

在你的錯誤的程序,大部分的時間可能是浪費了重新分配字符串,並將其打印到終端。

+1

天才!非常感謝 – dten

相關問題