1use std::time::Duration;
8
9#[cfg(target_os = "macos")]
12#[expect(
13 clippy::cast_possible_truncation,
14 reason = "The macOS Mach message count is defined as the platform ABI's bounded integer type."
15)]
16#[allow(
17 deprecated,
18 unsafe_code,
19 unused_qualifications,
20 reason = "Intentional compatibility, platform, or test-only suppression."
21)] pub fn resident_set_size_mb() -> Option<f64> {
23 let mut info: libc::mach_task_basic_info = unsafe { std::mem::zeroed() };
26 let mut count = (std::mem::size_of::<libc::mach_task_basic_info>() / std::mem::size_of::<libc::integer_t>())
27 as libc::mach_msg_type_number_t;
28 let task = unsafe { libc::mach_task_self() };
31 let ret = unsafe {
35 libc::task_info(
36 task,
37 libc::MACH_TASK_BASIC_INFO,
38 std::ptr::addr_of_mut!(info).cast::<libc::integer_t>(),
39 &mut count,
40 )
41 };
42 if ret != libc::KERN_SUCCESS {
43 return None;
44 }
45 Some(info.resident_size as f64 / (1024.0 * 1024.0))
46}
47
48#[cfg(target_os = "linux")]
51#[allow(
52 unsafe_code,
53 reason = "Intentional compatibility, platform, or test-only suppression."
54)]
55pub fn resident_set_size_mb() -> Option<f64> {
56 let contents = std::fs::read_to_string("/proc/self/statm").ok()?;
57 let field = contents.split_whitespace().nth(1)?;
58 let pages: f64 = field.parse().ok()?;
59 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as f64;
64 Some(pages * page_size / (1024.0 * 1024.0))
65}
66
67#[cfg(not(any(target_os = "macos", target_os = "linux")))]
69pub fn resident_set_size_mb() -> Option<f64> {
70 None
71}
72
73pub fn sample_rss_mb() -> f64 {
75 resident_set_size_mb().unwrap_or(0.0)
76}
77
78pub fn sample_peak_rss_mb(duration: Duration, poll_interval: Duration) -> f64 {
81 sample_peak_rss_mb_while(duration, poll_interval, || true)
82}
83
84pub fn sample_peak_rss_mb_while(
91 duration: Duration,
92 poll_interval: Duration,
93 mut should_continue: impl FnMut() -> bool,
94) -> f64 {
95 let start = std::time::Instant::now();
96 let mut peak: f64 = 0.0;
97 while should_continue() && start.elapsed() < duration {
98 peak = peak.max(sample_rss_mb());
99 std::thread::sleep(poll_interval);
100 }
101 peak
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn peak_sampler_stops_before_first_sample_when_predicate_is_false() {
110 let peak = sample_peak_rss_mb_while(Duration::from_secs(60), Duration::from_millis(1), || false);
111 assert_eq!(peak, 0.0);
112 }
113
114 #[test]
115 fn peak_sampler_observes_every_iteration_until_predicate_flips() {
116 let mut polls = 0;
117 let peak = sample_peak_rss_mb_while(Duration::from_secs(60), Duration::from_millis(1), || {
118 polls += 1;
119 polls <= 3
120 });
121 assert_eq!(polls, 4);
124 assert!(peak >= 0.0);
125 }
126}