clairlune_platform/
usage.rs1use std::time::Duration;
5
6pub fn process_cpu_time() -> Duration {
8 #[cfg(windows)]
9 {
10 crate::windows_live::process_cpu_time()
11 }
12 #[cfg(target_os = "macos")]
13 {
14 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
31pub fn process_memory() -> u64 {
33 #[cfg(windows)]
34 {
35 crate::windows_live::process_memory()
36 }
37 #[cfg(target_os = "macos")]
38 {
39 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 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}