Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Rust slower than my similar Python? [duplicate]

Tags:

rust

I have the following Rust program (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]);
}

According to the example at http://doc.rust-lang.org/std/io/ the above is the way to pull the lines of a file into a vector of strings. I've thrown in the output of the 500th line.

To solve the same task in Python I've written the following:

#!/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()

When I run the compiled Rust and time it I get this:

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

Running the Python gives:

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

I know that println! is a macro which expands to the more complex

::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)],
}));

Still, that doesn't seem like the sort of thing that would cause more than a second of additional execution time. Are these snippets of code not, in fact, similar? Have I misinterpreted the most efficient way to read lines into a vector and output one of them?

For reference nc.txt has the following properties:

rts@testbed $ du -hs nc.txt 
7.5M    nc.txt
rts@testbed $ wc -l nc.txt
   60219 nc.txt
like image 284
rts Avatar asked Jan 11 '15 09:01

rts


1 Answers

Build it with optimization flags.

cargo run --release
like image 54
geckob Avatar answered Oct 20 '22 16:10

geckob