I'm currently trying to learn Rust syntax while solving small tasks. I compare runtime as a health check if I use the language correctly.
One task:
- Create an array of 10,000,000 random numbers in the range 0 - 1,000,000,000
- Sort and measure time
- Print the time it is sorted
I got the following results:
| # | Language | Speed | LOCs |
| --- | -------------------- | ------ | ---- |
| 1 | C++ (with -O3) | 1.36s | 1 |
| 2 | Python (with PyPy) | 3.14s | 1 |
| 3 | Ruby | 5.04s | 1 |
| 4 | Go | 6.17s | 1 |
| 5 | C++ | 7.95s | 1 |
| 6 | Python (with Cython) | 11.51s | 1 |
| 7 | PHP | 36.28s | 1 |
Now I have written the following Rust code:
rust.rs
extern crate rand;
extern crate time;
use rand::Rng;
use time::PreciseTime;
fn main() {
let n = 10000000;
let mut array = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..n {
array.push(rng.gen::<i32>());
}
let start = PreciseTime::now();
array.sort();
let end = PreciseTime::now();
println!("{} seconds for sorting {} integers.", start.to(end), n);
}
with the following Cargo.toml :
[package]
name = "hello_world"
version = "0.0.1"
authors = [ "you@example.com" ]
[[bin]]
name = "rust"
path = "rust.rs"
[dependencies]
rand = "*"
time = "*"
I compiled it with cargo run rust.rsand ran the binary. He outputs
PT18.207168155S seconds for sorting 10000000 integers.
Please note that this is much slower than Python. I think I'm doing something wrong. (The full code for rust and other languages ββis here if you are interested.)
Rust? ?