为什么Rust比我的类似Python慢?

rts

我有以下Rust程序(rustc 1.0.0-nightly(44a287e6e 2015-01-08 17:03:40 -0800)):

use std::io::BufferedReader;
use std::io::File;

fn main() {
    let path = Path::new("nc.txt");
    let mut file = BufferedReader::new(File::open(&path));
    let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
    println!("{}", lines[500]);
}

根据http://doc.rust-lang.org/std/io/上的示例,以上是将文件的行拉入字符串向量的方法。我已经输入了第500行的输出。

为了解决Python中的相同任务,我编写了以下代码:

#!/usr/local/bin/python3

def main():
    with open('nc.txt', 'r') as nc:
        lines = nc.read().split('\n')
    print("{}".format(lines[500]))

if __name__ == '__main__':
    main()

当我运行编译的Rust并计时时,我得到以下信息:

rts@testbed $ time ./test
A declaration of independence by Kosovo will likely bring a similar declaration from Georgia's breakaway Abkhazia region, which Russia could well recognize.

./test  1.09s user 0.02s system 99% cpu 1.120 total

运行Python可以:

rts@testbed $ time ./test.py 
A declaration of independence by Kosovo will likely bring a similar declaration from Georgia's breakaway Abkhazia region, which Russia could well recognize.
./test.py  0.05s user 0.03s system 90% cpu 0.092 total

我知道这println!是一个宏,它会扩展为更复杂的宏

::std::io::stdio::println_args(::std::fmt::Arguments::new({
    #[inline]
    #[allow(dead_code)]
    static __STATIC_FMTSTR: &'static [&'static str] = &[""];
    __STATIC_FMTSTR
},
&match (&lines[500],) {
    (__arg0,) => [::std::fmt::argument(::std::fmt::String::fmt, __arg0)],
}));

尽管如此,这似乎并不会导致超过一秒钟的额外执行时间。这些代码片段实际上是否相似?我是否误解了将线读入向量并输出其中之一的最有效方法?

供参考,nc.txt具有以下属性:

rts@testbed $ du -hs nc.txt 
7.5M    nc.txt
rts@testbed $ wc -l nc.txt
   60219 nc.txt
壁虎

使用优化标志进行构建。

cargo run --release

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么最大的熊猫比我的慢?

为什么我的XLL比我的UDF慢?

为什么我的锈病比我的C记忆操纵慢?

为什么Linux内核中的bitops比我的慢?

为什么我的n log(n)堆排序比我的n ^ 2选择排序慢

为什么我的 aks prime test 的实现比我的 naive 版本的实现慢?

为什么Math.pow(int,int)比我的幼稚实现慢?

在某些情况下,国家的表现比我预期的要慢。为什么?

为什么__builtin_popcount比我自己的位计数功能慢?

为什么我的Rust程序比等效的Java程序慢?

为什么UIButton比我设置的大

为什么ScriptIntrinsicBlur比我的方法快?

为什么我教授的LU分解版本比我的分解更快?python numpy的

为什么从Torrent Magnet到Torrent的文件提取比我的python脚本快?

为什么我的包含范围比我的svg大?

为什么我的按钮插件比我的文本输入大?

为什么我的框架比我设定的要大?

为什么这个Rust程序这么慢?我错过了什么?

为什么我的python代码这么慢(leetcode)?

为什么在我的代码中numba比纯python慢?

为什么吐司出现的次数比我需要的次数多?

为什么这个版本的strrev比我的快?

为什么strcmp比我的函数快得多?

为什么这段代码比我的更高效?

为什么我执行阵列反转的Rust程序要比同等的Go程序慢?

函数调用开销-为什么内置Python内置函数看起来比我的内置函数快?

为什么在Rust中遍历整数向量比在Python,C#和C ++中慢?

为什么我创建的gif这么慢?

为什么我的Eratosthenes筛子这么慢?