dsa_rust/util/
cycle_counter.rs

1#![allow(unused)]
2#[cfg(target_arch = "x86_64")]
3use std::arch::x86_64::_rdtsc;
4
5#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
6pub struct CycleCount(u64);
7
8impl CycleCount {
9    #[inline(always)]
10    pub fn now() -> Self {
11        // 1. Miri Check: Must come first to intercept before hardware execution
12        #[cfg(miri)]
13        {
14            // Miri does not have real CPU cycles. We can simulate a monotonic
15            // counter using the standard library's Instant or an atomic counter.
16            static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
17            CycleCount(COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
18        }
19
20        // 2. x86_64 Hardware (Skip if under Miri)
21        #[cfg(all(target_arch = "x86_64", not(miri)))]
22        unsafe {
23            CycleCount(std::arch::x86_64::_rdtsc())
24        }
25
26        // 3. AArch64 Hardware (Skip if under Miri)
27        #[cfg(all(target_arch = "aarch64", not(miri)))]
28        {
29            let ticks: u64;
30            unsafe {
31                std::arch::asm!("mrs {}, cntvct_el0", out(reg) ticks);
32            }
33            CycleCount(ticks)
34        }
35
36        // 4. Catch-all fallback for unsupported architectures when not covered above
37        #[cfg(not(any(miri, target_arch = "x86_64", target_arch = "aarch64")))]
38        {
39            // Fall back to system time context if no native assembly is written
40            static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
41            let start = START.get_or_init(std::time::Instant::now);
42            CycleCount(start.elapsed().as_nanos() as u64)
43        }
44    }
45
46    #[inline(always)]
47    pub fn cycles_since(&self, earlier: CycleCount) -> u64 {
48        self.0.saturating_sub(earlier.0)
49    }
50}