以下是我的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
和
rustc set_performance.rs -O
time ./set_performance 50000000
real 0m17.580s
user 0m17.533s
sys 0m0.032s
Building with cargo
和 --release
give the same result.
I realize that Python's set
is implemented in C, 和 so is expected to be fast, but I did not expect it to be faster than Rust. Wouldn't it have to do extra type checking that Rust would not?
也许我在编译我的Rust程序时遗漏了一些东西,我应该使用其他优化标志吗?
Another possibility is that the code is not really equivalent, 和 Rust is doing unnecessary extra work, am I missing anything?
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]'
铁 rust 版
$ rustc --version
rustc 1.5.0 (3d7cd77e4 2015-12-04)
I am using Ubuntu 14.04 和 my system architecture is x86_64.