use std::sync::atomic::{AtomicBool, Ordering};
static TRACE: AtomicBool = AtomicBool::new(false);
pub fn set_enabled(on: bool) {
TRACE.store(on, Ordering::Relaxed);
}
pub fn enabled() -> bool {
TRACE.load(Ordering::Relaxed)
}
fn rss_mb() -> u64 {
match std::fs::read_to_string("/proc/self/statm") {
Ok(s) => {
let resident_pages: u64 = s
.split_whitespace()
.nth(1)
.and_then(|f| f.parse().ok())
.unwrap_or(0);
resident_pages * 4096 / (1024 * 1024)
}
Err(_) => 0,
}
}
fn peak_mb() -> u64 {
match std::fs::read_to_string("/proc/self/status") {
Ok(s) => s
.lines()
.find_map(|l| l.strip_prefix("VmHWM:"))
.and_then(|v| v.split_whitespace().next())
.and_then(|kb| kb.parse::<u64>().ok())
.map(|kb| kb / 1024)
.unwrap_or(0),
Err(_) => 0,
}
}
pub fn probe(label: &str) {
if enabled() {
eprintln!(
"[trace-rss] {label} RSS={} MB (peak {} MB)",
rss_mb(),
peak_mb()
);
}
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
unsafe extern "C" {
fn malloc_trim(pad: usize) -> i32;
}
pub fn trim() {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
unsafe {
malloc_trim(0);
}
}