Skip to main content

clairlune_platform/
usage.rs

1//! What this process uses, for the log: CPU time so far, and memory now
2//! (on macOS the footprint Activity Monitor shows, GPU surfaces included).
3
4use std::time::Duration;
5
6/// CPU time (user and system) the process has used so far.
7pub fn process_cpu_time() -> Duration {
8    #[cfg(windows)]
9    {
10        crate::windows_live::process_cpu_time()
11    }
12    #[cfg(target_os = "macos")]
13    {
14        // SAFETY: getrusage fills the struct it is given.
15        let mut r: libc::rusage = unsafe { std::mem::zeroed() };
16        if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut r) } != 0 {
17            return Duration::ZERO;
18        }
19        let tv = |t: libc::timeval| {
20            Duration::from_secs(t.tv_sec.max(0) as u64)
21                + Duration::from_micros(t.tv_usec.max(0) as u64)
22        };
23        tv(r.ru_utime) + tv(r.ru_stime)
24    }
25    #[cfg(not(any(windows, target_os = "macos")))]
26    {
27        Duration::ZERO
28    }
29}
30
31/// Memory the process holds now, in bytes (0 where unknown).
32pub fn process_memory() -> u64 {
33    #[cfg(windows)]
34    {
35        crate::windows_live::process_memory()
36    }
37    #[cfg(target_os = "macos")]
38    {
39        // SAFETY: proc_pid_rusage fills a rusage_info_v2 for this flavour.
40        let mut info: libc::rusage_info_v2 = unsafe { std::mem::zeroed() };
41        let ok = unsafe {
42            libc::proc_pid_rusage(
43                libc::getpid(),
44                libc::RUSAGE_INFO_V2,
45                (&mut info as *mut libc::rusage_info_v2).cast(),
46            )
47        } == 0;
48        if ok { info.ri_phys_footprint } else { 0 }
49    }
50    #[cfg(not(any(windows, target_os = "macos")))]
51    {
52        0
53    }
54}
55
56#[cfg(all(test, any(windows, target_os = "macos")))]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn this_process_uses_something() {
62        // Burn CPU until the clock moves (Windows counts in 15.6 ms ticks).
63        let start = std::time::Instant::now();
64        let mut x = 0u64;
65        while process_cpu_time() == Duration::ZERO && start.elapsed() < Duration::from_secs(5) {
66            for i in 0..1_000_000u64 {
67                x = std::hint::black_box(x.wrapping_mul(31).wrapping_add(i));
68            }
69        }
70        assert!(process_cpu_time() > Duration::ZERO);
71        assert!(process_memory() > 0);
72    }
73}