我正在尝试重现处理器缓存效果库的示例 6 。
文章以这个函数(在 C# 中)为例如何测试虚假共享:
private static int[] s_counter = new int[1024];
private void UpdateCounter(int position)
{
for (int j = 0; j < 100000000; j++)
{
s_counter[position] = s_counter[position] + 3;
}
}
如果我们创建传递给这个函数 0、1、2、3 个参数的线程,计算将需要很长时间才能完成(作者得到了 4.3 秒)。例如,如果我们通过 16、32、48、64,我们会得到更好的结果(0.28 秒)。
我在 Rust 中提出了以下函数:
pub fn cache_line_sharing(arr: [i32; 128], pos: usize) -> (i32, i32) {
let arr = Arc::new(arr);
let handles: Vec<_> = (0..4).map(|thread_number| {
let arr = arr.clone();
let pos = thread_number * pos;
thread::spawn(move || unsafe {
let p = (arr.as_ptr() as *mut i32).offset(pos as isize);
for _ in 0..1_000_000 {
*p = (*p).wrapping_add(3);
}
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
(arr[0], arr[1])
}
用两组参数(0、1、2、3 和 0、16、32、48)对其进行基准测试,得到了几乎相同的结果:108.34 和 105.07 微秒。
我使用标准箱作为基准。我有一台配备 Intel i5-5257U CPU (2.70GHz) 的 MacBook Pro 2015。我的系统报告有64B
缓存行大小。
如果有人想查看我的完整基准测试代码,请点击以下链接:- lib.rs - cache_lines.rs
我想了解问题并找到重现文章中类似结果的方法。