pub fn emit_marker(name: &str) {
use std::io::Write;
write_fifo(|f, us| { drop((&*f).write_all(format!("{us} {name}\n").as_bytes())); });
}
pub fn emit_counter(name: &str, value: i64) {
use std::io::Write;
write_fifo(|f, us| { drop((&*f).write_all(format!("{us} @{name}={value}\n").as_bytes())); });
}
#[cfg(target_os = "linux")]
pub fn emit_mallinfo2(prefix: &str) {
let info = unsafe { libc::mallinfo2() };
#[allow(clippy::cast_possible_wrap)]
{
emit_counter(&format!("{prefix}_arena"), info.arena as i64);
emit_counter(&format!("{prefix}_hblks"), info.hblks as i64);
emit_counter(&format!("{prefix}_hblkhd"), info.hblkhd as i64);
emit_counter(&format!("{prefix}_uordblks"), info.uordblks as i64);
emit_counter(&format!("{prefix}_fordblks"), info.fordblks as i64);
emit_counter(&format!("{prefix}_keepcost"), info.keepcost as i64);
}
}
#[cfg(not(target_os = "linux"))]
pub fn emit_mallinfo2(_prefix: &str) {}
#[cfg(target_os = "linux")]
pub fn read_page_faults() -> (u64, u64) {
let Ok(stat) = std::fs::read_to_string("/proc/self/stat") else {
return (0, 0);
};
let mut fields = stat.split_whitespace();
let minflt = fields.nth(9).and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);
let majflt = fields.nth(1).and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);
(minflt, majflt)
}
#[cfg(not(target_os = "linux"))]
pub fn read_page_faults() -> (u64, u64) {
(0, 0)
}
fn write_fifo(f: impl FnOnce(&std::fs::File, u128)) {
use std::sync::OnceLock;
static STATE: OnceLock<Option<(std::fs::File, std::time::Instant)>> = OnceLock::new();
let state = STATE.get_or_init(|| {
let path = std::env::var("BROKKR_MARKER_FIFO").ok()?;
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
#[cfg(target_os = "linux")]
const O_NONBLOCK: i32 = 0x800;
#[cfg(target_os = "macos")]
const O_NONBLOCK: i32 = 0x0004;
let file = std::fs::OpenOptions::new()
.write(true)
.custom_flags(O_NONBLOCK)
.open(&path)
.ok()?;
Some((file, std::time::Instant::now()))
}
#[cfg(not(unix))]
{
let _ = path;
None
}
});
if let Some((file, start)) = state.as_ref() {
let us = start.elapsed().as_micros();
f(file, us);
}
}