【发布时间】:2017-08-02 08:18:05
【问题描述】:
考虑这个程序:
use std::io::BufRead;
use std::io;
fn main() {
let mut n = 0;
let stdin = io::stdin();
for _ in stdin.lock().lines() {
n += 1;
}
println!("{}", n);
}
为什么它比 GNU 版本的 wc 慢 10 倍以上?看看我是如何测量它的:
$ yes | dd count=1000000 | wc -l
256000000
1000000+0 records in
1000000+0 records out
512000000 bytes (512 MB, 488 MiB) copied, 1.16586 s, 439 MB/s
$ yes | dd count=1000000 | ./target/release/wc
1000000+0 records in
1000000+0 records out
512000000 bytes (512 MB, 488 MiB) copied, 41.685 s, 12.3 MB/s
256000000
【问题讨论】:
-
只是一个猜测,但是:我会说
wc可能不会为每一行分配一个新的动态调整大小的字符串。 -
用 Rust 为 Redox 编写的 coreutils 最少;你可以查看their implementation of wc。
-
将其描述为“Rust 的 wc 版本”而不是 您的 版本的
wc是不是有点不对劲? -
@Damien_The_Unbeliever 你可能会争论两种方式——要么我没有很好地优化它(从我在这里得到的答案来看,这并不简单)或者 Rust 没有。
标签: rust benchmarking gnu-coreutils