Skip to main content

subetha_cxc/
cpu_affinity.rs

1//! Cross-platform CPU core pinning for controlled measurements.
2//!
3//! Pinning the producer and consumer to fixed, distinct cores removes
4//! the run-to-run scheduler variance that otherwise swamps small
5//! cache-coherence effects in a 1P/1C throughput measurement. The
6//! function is best-effort: it returns `false` (leaving the thread on
7//! the OS default) on platforms without a supported affinity API, so
8//! a caller can report that its measurement was uncontrolled rather
9//! than silently trusting a noisy number.
10
11/// Pin the calling thread to a single logical core. Returns `true`
12/// if the affinity was actually set.
13#[cfg(target_os = "windows")]
14pub fn pin_current_thread_to_core(core: usize) -> bool {
15    use windows_sys::Win32::System::Threading::{
16        GetCurrentThread, SetThreadAffinityMask,
17    };
18    if core >= usize::BITS as usize {
19        return false;
20    }
21    let mask: usize = 1usize << core;
22    // Returns the previous affinity mask, or 0 on failure.
23    unsafe { SetThreadAffinityMask(GetCurrentThread(), mask) != 0 }
24}
25
26/// Pin the calling thread to a single logical core. Returns `true`
27/// if the affinity was actually set.
28#[cfg(target_os = "linux")]
29pub fn pin_current_thread_to_core(core: usize) -> bool {
30    unsafe {
31        let mut set: libc::cpu_set_t = std::mem::zeroed();
32        libc::CPU_ZERO(&mut set);
33        libc::CPU_SET(core, &mut set);
34        libc::sched_setaffinity(
35            0,
36            std::mem::size_of::<libc::cpu_set_t>(),
37            &set,
38        ) == 0
39    }
40}
41
42/// Best-effort no-op on platforms without a supported affinity API.
43#[cfg(not(any(target_os = "windows", target_os = "linux")))]
44pub fn pin_current_thread_to_core(_core: usize) -> bool {
45    false
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn pin_to_core_zero() {
54        // Core 0 exists everywhere; on a supported platform the pin
55        // succeeds, elsewhere it is the documented no-op.
56        let ok = pin_current_thread_to_core(0);
57        #[cfg(any(target_os = "windows", target_os = "linux"))]
58        assert!(ok, "pinning to core 0 should succeed on this platform");
59        #[cfg(not(any(target_os = "windows", target_os = "linux")))]
60        assert!(!ok);
61    }
62}