pub fn physical_cores() -> Vec<usize> {
let mut seen = std::collections::HashSet::new();
let mut physical = Vec::new();
for cpu_id in 0..1024 {
let path = format!(
"/sys/devices/system/cpu/cpu{}/topology/core_id",
cpu_id
);
match std::fs::read_to_string(&path) {
Ok(s) => {
if let Ok(core_id) = s.trim().parse::<usize>() {
if seen.insert((cpu_id / 64, core_id)) {
physical.push(cpu_id);
}
}
}
Err(_) => break,
}
}
if physical.is_empty() {
let n = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
(0..n).collect()
} else {
physical
}
}
pub fn pin_to_cpu(cpu_id: usize) {
#[cfg(target_os = "linux")]
unsafe {
let mut set = std::mem::zeroed::<libc::cpu_set_t>();
libc::CPU_SET(cpu_id, &mut set);
libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set);
}
#[cfg(not(target_os = "linux"))]
let _ = cpu_id;
}