我用Rust和Python编写了使用dict和hashmap执行相同计算的脚本。不知何故,Python版本要快10倍以上。这是怎么发生的?
锈脚本:'
use std::collections::HashMap;
use std::time::Instant;
fn main() {
let now = Instant::now();
let mut h = HashMap::new();
for i in 0..1000000 {
h.insert(i, i);
}
let elapsed = now.elapsed();
println!("Elapsed: {:.2?}", elapsed);
}
输出:Elapsed: 828.73ms
Python脚本:
import time
start = time.time()
d = dict()
for i in range(1000000):
d[i] = i
print(f"Elapsed: {(time.time() - start) * 1000:.2f}ms")
输出:Elapsed: 64.93ms
对于字符串键也是如此。我为HashMap搜索了不同哈希器的不同解决方案,但没有一个能提供超过10倍的速度
Rust默认不启用优化,因为这对调试来说很烦人。这使得它在调试模式下比Python慢。启用优化应该可以解决这个问题。
这种行为不是Rust特有的,它是大多数编译器的默认设置(如C/c++的gcc/g++
或clang
,都需要-O3
标志以获得最佳性能)。
你可以通过在相应的cargo
命令中添加--release
标志来启用Rust中的优化,如:
cargo run --release
Python不区分是否进行了优化,因为Python是一种解释性语言,并且没有(显式的)编译步骤。
这是你的代码在我的机器上的行为:
- Python: ~ 180 ms
- Rust: ~1750 ms
- Rust (with
--release
): ~160ms
Python的dict
实现很可能是用C编写的,并且经过了大量优化,所以它应该在性能上与Rust的HashMap
相似,这正是我在我的机器上看到的。