我目前正在尝试通过解决小任务来学习Rust的语法。如果我以正确的方式使用该语言,我将执行时间作为健全性检查进行比较。
一项任务是:
我得到了以下结果:
| # | 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 |
现在我写了以下Rust代码:
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[i] = rng.gen::<i32>();
array.push(rng.gen::<i32>());
}
// Sort
let start = PreciseTime::now();
array.sort();
let end = PreciseTime::now();
println!("{} seconds for sorting {} integers.", start.to(end), n);
}
使用以下 Cargo.toml :
[package]
name = "hello_world" # the name of the package
version = "0.0.1" # the current version, obeying semver
authors = [ "you@example.com" ]
[[bin]]
name = "rust"
path = "rust.rs"
[dependencies]
rand = "*" # Or a specific version
time = "*"
我用cargo run rust.rs
编译它并运行二进制文件。它输出
PT18.207168155S seconds for sorting 10000000 integers.
请注意,这比Python要慢得多。我想我做错了什么。 (如果您感兴趣,完整的生锈代码和其他语言代码为here。)
为什么用Rust排序需要这么长时间?我怎样才能让它更快?
答案 0 :(得分:11)
我在计算机上尝试了您的代码,并使用cargo run
运行它:
PT11.634640178S seconds for sorting 10000000 integers.
使用cargo run --release
(启用优化)会给出:
PT1.004434739S seconds for sorting 10000000 integers.