I have this simple Rust program, which creates a file called numbers.txt
and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:
use std::fs::File;
use std::io::Write;
const N: i32 = 1e7 as i32;
fn main() {
let mut data = String::new();
for i in 1..=N {
data.push_str(&format!("{0}\n", i));
}
let mut f = File::create("numbers.txt").expect("Unable to create file");
f.write_all(data.as_bytes()).expect("Unable to write data");
}
I've been running and timing the program with:
$ time cargo run --release
numbers.txt
after running:
1
2
3
4
...
9999999
10000000
I've timed the execution of the program, and it takes around 4.8 seconds to run on my machine. I tried timing just the string building, by commenting out the last two lines, and the time taken stayed pretty much the same. We can conclude that the bottleneck is the data
string building and not writing to the file.
How could I make building data
faster? Should I use something else than a String
?
cargo run --release
to run the code. And actually$ time cargo run --release
, when I needed to see the execution time. \$\endgroup\$