这是我的Python代码:
len_sums = 0
for i in xrange(100000):
set_1 = set(xrange(1000))
set_2 = set(xrange(500, 1500))
intersection_len = len(set_1.intersection(set_2))
len_sums += intersection_len
print len_sums
这是我的 Rust 代码:
use std::collections::HashSet;
fn main() {
let mut len_sums = 0;
for _ in 0..100000 {
let set_1: HashSet<i32> = (0..1000).collect();
let set_2: HashSet<i32> = (500..1500).collect();
let intersection_len = set_1.intersection(&set_2).count();
len_sums += intersection_len;
}
println!("{}", len_sums);
}
我相信这些大致相当。我得到以下性能结果:
time python set_performance.py
50000000
real 0m11.757s
user 0m11.736s
sys 0m0.012s
and
rustc set_performance.rs -O
time ./set_performance 50000000
real 0m17.580s
user 0m17.533s
sys 0m0.032s
建筑与cargo
and --release
给出相同的结果。
我意识到Python的set
是用C实现的,所以预计会很快,但没想到比Rust还快。难道它不需要进行 Rust 不需要的额外类型检查吗?
也许我在编译 Rust 程序的方式中遗漏了一些东西,是否还有我应该使用的其他优化标志?
另一种可能性是代码并不真正等效,Rust 正在做不必要的额外工作,我是否遗漏了什么?
Python版本:
In [3]: import sys
In [4]: sys.version
Out[4]: '2.7.6 (default, Jun 22 2015, 17:58:13) \n[GCC 4.8.2]'
锈版
$ rustc --version
rustc 1.5.0 (3d7cd77e4 2015-12-04)
我使用的是 Ubuntu 14.04,我的系统架构是 x86_64。