diff --git a/crates/native-cpu-expert/examples/kernel_ab.rs b/crates/native-cpu-expert/examples/kernel_ab.rs index 5e2689a4..fa710b78 100644 --- a/crates/native-cpu-expert/examples/kernel_ab.rs +++ b/crates/native-cpu-expert/examples/kernel_ab.rs @@ -1024,14 +1024,14 @@ fn sibling_idle(cpu: usize) -> bool { } fn rustc_info() -> (String, String) { - let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()); + // $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH) + let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default(); + let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" }); + let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim]; let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" }; - let version = Command::new(rustc) - .arg("--version") - .output() - .ok() - .filter(|o| o.status.success()) - .and_then(|o| String::from_utf8(o.stdout).ok()) + let version = candidates + .iter() + .find_map(|rustc| Command::new(rustc).arg("--version").output().ok().filter(|o| o.status.success()).and_then(|o| String::from_utf8(o.stdout).ok())) .map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned()); (version, triple.to_owned()) } @@ -1221,31 +1221,33 @@ const CLOCK_MOVED_FRACTION: f64 = 0.05; /// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). const SIBLING_BUSY_LIMIT: f64 = 0.05; const ALIGN: usize = 4096; -/// Latency of a dependent 64-bit multiply in cycles on every core the A/B runs on (Intel Skylake to Golden Cove, AMD Zen 1 to 5). -const MUL_LATENCY_CYCLES: f64 = 3.0; -const CLOCK_METHOD: &str = "chain of dependent 64-bit multiplies (latency 3 cycles), 1000000 iterations of 4, ghz = 3 * 4e6 / (elapsed ns); before and after every slice"; +/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove +/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. +const CHAIN_STEP_CYCLES: f64 = 4.0; +const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice"; fn mono_ns() -> u64 { static ORIGIN: OnceLock = OnceLock::new(); ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64 } -/// The core clock in GHz from a chain of dependent multiplies (safe code: the C++ chain of dependent adds needs inline assembly). The -/// constant is opaque to the optimiser, so the four multiplies per iteration stay four dependent instructions. +/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain +/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the +/// running value, which no reassociation can remove. fn core_ghz() -> f64 { let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); let mut x = std::hint::black_box(1u64); let n = 1_000_000u64; let t0 = mono_ns(); for _ in 0..n { - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); - x = x.wrapping_mul(k); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); } let dt = mono_ns().saturating_sub(t0).max(1); std::hint::black_box(x); - MUL_LATENCY_CYCLES * 4.0 * n as f64 / dt as f64 + CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64 } fn median_of(v: &[f64]) -> f64 { @@ -1863,8 +1865,10 @@ fn procs_for(trees: &[&'static str]) -> Vec { v } -/// The environment a cell needs and nothing else: the Rust cells keep the pool from re-pinning its caller (the pin is the requested -/// one); the avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. +/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The +/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must +/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch +/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time). fn cell_env(p: &Proc) -> Vec<(String, String)> { let mut v = Vec::new(); if p.tree == "avx2" { @@ -1872,6 +1876,7 @@ fn cell_env(p: &Proc) -> Vec<(String, String)> { } if p.imp == Impl::Rust { v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned())); + v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())); } v.sort(); v @@ -2236,8 +2241,10 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); for tree in trees { @@ -2275,6 +2282,9 @@ fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result Result ... " before the child's own output on the same line let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); probes.sort_unstable(); - assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1"], "only the cell's variables survive:\n{text}"); + assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], "only the cell's variables survive:\n{text}"); // the cpp avx512 cell sets nothing at all let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap(); assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); @@ -3110,7 +3123,9 @@ mod tests { assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); assert_eq!(busy_fraction(None, Some((1, 1))), None); - assert!(core_ghz() > 0.0); + // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain) + let ghz = core_ghz(); + assert!((0.3..12.0).contains(&ghz), "{ghz}"); } #[test] @@ -3228,6 +3243,7 @@ mod tests { }; let mut done: Vec = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); done.reverse(); // the order of execution does not matter to the records + done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = Some(false); let files = round_records(&ctx, 31, &done).unwrap(); assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); @@ -3263,6 +3279,12 @@ mod tests { let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b")); assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); + // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b + for (name, json) in &files { + let rec = parse_json(json.as_bytes()).unwrap(); + let busy = name.contains(".aa-cpp.avx2."); + assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); + } // a streamed set that differs between the two sides of a record is refused let mut skewed = done.clone(); skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4;