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(unix)]
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, unix)))]
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(target_os = "linux")]
51 {
52 let pages = std::fs::read_to_string("/proc/self/statm")
54 .ok()
55 .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
56 .unwrap_or(0);
57 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }.max(0) as u64;
59 pages * page
60 }
61 #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
62 {
63 0
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn this_process_uses_something() {
73 let start = std::time::Instant::now();
75 let mut x = 0u64;
76 while process_cpu_time() == Duration::ZERO && start.elapsed() < Duration::from_secs(5) {
77 for i in 0..1_000_000u64 {
78 x = std::hint::black_box(x.wrapping_mul(31).wrapping_add(i));
79 }
80 }
81 assert!(process_cpu_time() > Duration::ZERO);
82 assert!(process_memory() > 0);
83 }
84}