use libc::rusage;
pub fn peak_rss_bytes() -> u64 {
let mut usage: rusage = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut usage as *mut rusage) };
if rc != 0 {
return 0;
}
let raw = usage.ru_maxrss as u64;
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
raw }
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
raw.saturating_mul(1024) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn peak_rss_reflects_a_real_allocation_in_bytes() {
let n = 64usize * 1024 * 1024;
let mut buf = vec![0u8; n];
let mut i = 0;
while i < n {
buf[i] = 1;
i += 4096;
}
std::hint::black_box(&buf);
let peak = peak_rss_bytes();
assert!(
peak >= 32 * 1024 * 1024,
"peak RSS {peak} bytes implausibly small after a 64 MiB allocation \
(a dropped KiB->bytes conversion would land here)"
);
}
}