当两个64位数乘以两个32位数时,我正在测量锈蚀的性能。回想一下,64乘法的结果是128数字,32位乘法的结果是64位数。我预计64位乘法至少比另一位慢2倍。主要是因为没有本地128位支持,并且要将两个64位数相乘,您可以将它们分为32位、上下两位。然而,当我运行测试时,结果发现两者的性能都是相似的。
下面是我使用的脚本:
fn main() {
test_64_mul();
test_32_mul();
}
fn test_64_mul() {
let test_num: u64 = 12345678653435363454;
use std::time::Instant;
let mut now = Instant::now();
let mut elapsed = now.elapsed();
for _ in 1..2000 {
now = Instant::now();
let _prod = test_num as u128 * test_num as u128;
elapsed = elapsed + now.elapsed();
}
println!("Elapsed For 64: {:.2?}", elapsed);
}
fn test_32_mul() {
let test_num: u32 = 1234565755;
use std::time::Instant;
let mut now = Instant::now();
let mut elapsed = now.elapsed();
for _ in 1..2000 {
now = Instant::now();
let _prod = test_num as u64 * test_num as u64;
elapsed = elapsed + now.elapsed();
}
println!("Elapsed For 32: {:.2?}", elapsed);
}运行此代码后的输出是
64: 25.58秒
32: 26.08 s
我正在使用MacBook Pro与M1芯片和铁锈版本1.60.0
发布于 2022-05-25 06:37:53
因为编译器注意到您没有使用结果,因此完全消除了乘法。
参见https://rust.godbolt.org/z/5sjze7Mbv的差异。
您应该使用类似std::hint::black_box()或者更好的基准测试框架,比如标准。
而且,每次创建一个新的Instant的开销可能比乘法本身的开销要高得多。就像我说的,使用基准框架。
正如@StephenC所指出的,时钟分辨率也不太可能小到足以测量一个乘法。
https://stackoverflow.com/questions/72372738
复制相似问题