Skip to main content

aft_base/clock/
cpu_time.rs

1//! Thread CPU samples, never process CPU or elapsed wall time.
2
3use std::thread::ThreadId;
4use std::time::Duration;
5
6#[derive(Clone, Copy, Debug)]
7pub struct ThreadCpuSample {
8    thread: ThreadId,
9    cpu: Duration,
10}
11
12impl ThreadCpuSample {
13    pub fn now() -> Option<Self> {
14        Some(Self {
15            thread: std::thread::current().id(),
16            cpu: thread_cpu_time()?,
17        })
18    }
19
20    pub fn elapsed(start: Option<Self>, end: Option<Self>) -> Option<Duration> {
21        let (start, end) = (start?, end?);
22        if start.thread != end.thread {
23            return None;
24        }
25        end.cpu.checked_sub(start.cpu)
26    }
27}
28
29#[cfg(any(target_os = "linux", target_os = "macos"))]
30fn thread_cpu_time() -> Option<Duration> {
31    let mut time = std::mem::MaybeUninit::<libc::timespec>::uninit();
32    // The OS initializes the timespec on success; no clock value is used on failure.
33    if unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, time.as_mut_ptr()) } != 0 {
34        return None;
35    }
36    let time = unsafe { time.assume_init() };
37    Some(Duration::new(
38        time.tv_sec.try_into().ok()?,
39        time.tv_nsec.try_into().ok()?,
40    ))
41}
42
43#[cfg(windows)]
44fn thread_cpu_time() -> Option<Duration> {
45    // GetThreadTimes is tick-quantized: a sub-millisecond phase can be charged
46    // an entire timer tick. Thread cycles have no reliable portable conversion
47    // to CPU time, so report unknown rather than a misleading duration.
48    None
49}
50
51#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
52fn thread_cpu_time() -> Option<Duration> {
53    None
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn cpu_phase_clock_failure_is_unknown() {
62        assert_eq!(ThreadCpuSample::elapsed(None, ThreadCpuSample::now()), None);
63        assert_eq!(ThreadCpuSample::elapsed(ThreadCpuSample::now(), None), None);
64    }
65
66    #[cfg(windows)]
67    #[test]
68    fn cpu_phase_windows_clock_is_unknown() {
69        assert_eq!(thread_cpu_time(), None);
70        assert!(ThreadCpuSample::now().is_none());
71    }
72
73    #[cfg(any(target_os = "linux", target_os = "macos"))]
74    #[test]
75    #[ignore = "clock-read microbenchmark, run explicitly with --ignored --nocapture"]
76    fn cpu_phase_clock_overhead() {
77        use std::hint::black_box;
78        use std::time::Instant;
79
80        const N: u32 = 100_000;
81        let start = Instant::now();
82        for _ in 0..N {
83            black_box(Instant::now());
84        }
85        let wall_only = start.elapsed();
86        let start = Instant::now();
87        for _ in 0..N {
88            black_box(Instant::now());
89            black_box(ThreadCpuSample::now());
90        }
91        let paired = start.elapsed();
92        println!(
93            "{N} boundaries: wall-only={:.1} ns, wall+CPU={:.1} ns, added={:.1} ns/boundary",
94            wall_only.as_nanos() as f64 / f64::from(N),
95            paired.as_nanos() as f64 / f64::from(N),
96            paired.saturating_sub(wall_only).as_nanos() as f64 / f64::from(N)
97        );
98    }
99}