Skip to main content

competitive/tools/
huge_pages.rs

1#[inline]
2pub fn advise_huge_pages<T>(_values: &mut Vec<T>) {
3    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
4    unsafe {
5        unsafe extern "C" {
6            fn madvise(
7                addr: *mut std::ffi::c_void,
8                len: usize,
9                advice: std::ffi::c_int,
10            ) -> std::ffi::c_int;
11        }
12        const PAGE_SIZE: usize = 1 << 12;
13        const MADV_HUGEPAGE: std::ffi::c_int = 14;
14        let ptr = _values.as_mut_ptr().cast::<u8>();
15        let offset = ptr.align_offset(PAGE_SIZE);
16        let len = (_values.capacity() * size_of::<T>()).saturating_sub(offset) & !(PAGE_SIZE - 1);
17        if len >= 1 << 20 {
18            // The hint covers only owned pages; initialization also works without it.
19            let _ = madvise(ptr.add(offset).cast(), len, MADV_HUGEPAGE);
20        }
21    }
22}