试图通过 unsafe 绕过越界检查看越界检查有多少额外开销

1次阅读

共计 1064 个字符,预计需要花费 3 分钟才能阅读完成。

结果在我的 M2 Mac mini 上,

  • 有边界检查: 1152 ms
  • 无边界检查: 1084 ms

基本是 6% 左右的时间开销 (不确定我这个封装是否有额外开销).

附源代码:

struct Array(*mut T);

impl From<*const T> for Array {fn from(ptr: *const T) -> Self {Self(ptr as *mut _)
    }
}

impl std::ops::Index for Array {
    type Output = T;
    fn index(&self, index: usize) -> &Self::Output {
        unsafe {let ptr = self.0.offset(index as isize);
            &*ptr
        }
    }
}
impl std::ops::IndexMut for Array {fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        unsafe {let ptr = self.0.offset(index as isize);
            &mut *ptr
        }
    }
}

fn main() {
    const SIZE: usize = 1024 * 1024;
    const LOOP: usize = 2_000_000;

    let mut arr = vec![0u32; SIZE];
    let start = std::time::Instant::now();
    // array indexing with boundary check
    {
        for _ in 0..LOOP {let index = rand::random::() % SIZE;
            arr[index] += 1;
        }
    }
    let elapsed = start.elapsed();
    println!("Array indexing with boundary check runtime: {}ms", elapsed.as_millis());

    // to avoid cache, use a different raw array.
    let mut arr = Array::from(vec![0u32; SIZE].as_ptr());
    let start = std::time::Instant::now();
    // array indexing wthout boundary check
    {
        for _ in 0..LOOP {let index = rand::random::() % SIZE;
            arr[index] += 1;
        }
    }
    let elapsed = start.elapsed();
    println!("Array indexing without boundary check runtime: {}ms", elapsed.as_millis());
    
}
正文完
 0