Skip to content

Commit 395613a

Browse files
committed
perf: added lfence instructions to prevent out-of-order counter profiling
1 parent 1abaeb9 commit 395613a

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

src/pmc.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,25 @@ pub fn read_cache_misses() -> u64 {
7474
unsafe { rdpmc(0) }
7575
}
7676

77-
/// Measure LLC cache misses during a closure
78-
/// Returns (result, cache_misses, cycles)
7977
pub fn measure<F, R>(f: F) -> (R, u64, u64)
8078
where
8179
F: FnOnce() -> R,
8280
{
81+
// Serialize instructions before capturing start telemetry
82+
unsafe { core::arch::asm!("lfence", options(nomem, nostack, preserves_flags)); }
83+
8384
let cycles_start = crate::benchmark::read_tsc();
8485
let misses_start = read_cache_misses();
8586

87+
// Compiler barrier: prevent optimization reordering across this boundary
88+
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
89+
8690
let result = f();
8791

92+
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
93+
// Serialize instructions before capturing end telemetry
94+
unsafe { core::arch::asm!("lfence", options(nomem, nostack, preserves_flags)); }
95+
8896
let misses_end = read_cache_misses();
8997
let cycles_end = crate::benchmark::read_tsc();
9098

0 commit comments

Comments
 (0)