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
Build it with optimization flags.
cargo run --release
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With