Hey guys! I'm new to Rust and I'm doing some experiments to familiarize myself with the language. I created code in Python and Rust that reads 999,999 integers from a file and sorts and reverses them. But my Python code runs in 1.8 seconds, while the Rust code (compiled with the --release flag) runs in 2.9 seconds. Any tips on how to speed up this code? I tried adding file and stdout read buffers but to no avail.
Python code:
import time
from io import StringIO
st = time.time()
text_stream = StringIO()
f = open("random_numbers.txt", "r")
lines = f.readlines()
numbers = list(map(lambda x : int(x.strip()), lines))
numbers.sort()
numbers.reverse()
for n in numbers:
text_stream.write(str(n)+"\n")
f.close()
print(text_stream.getvalue())
text_stream.close()
et = time.time()
elapsed_time = et - st
print('Execution time:', elapsed_time, 'seconds')
Rust code:
use std::fs::File;
use std::io::{stdout, Write};
use std::io::BufReader;
use std::io::prelude::*;
use std::time::Instant;
fn main() -> std::io::Result<()> {
let start = Instant::now();
let file = File::open("random_numbers.txt")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
let mut numbers = contents
.lines()
.map(|x| {
x.parse::<u32>()
.expect("Not find a u32 number")
})
.collect::<Vec<u32>>();
numbers.sort();
numbers.reverse();
let mut lock = stdout().lock();
for n in numbers {
writeln!(lock,"{}", n).unwrap();
}
let duration = start.elapsed();
println!("Time elapsed in expensive_function() is: {:?}", duration);
Ok(())
}