use std::cell::Cell;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
fn start() -> Option<Instant> {
static START: OnceLock<Option<Instant>> = OnceLock::new();
*START.get_or_init(|| std::env::var_os("RETEX_TIMING").map(|_| Instant::now()))
}
pub fn enabled() -> bool {
start().is_some()
}
pub fn mark(label: &str) {
if let Some(t0) = start() {
eprintln!(
"[timing] {:>9.3} ms {label}",
t0.elapsed().as_secs_f64() * 1e3
);
}
}
#[derive(Default)]
pub struct Accumulator {
total: Cell<Duration>,
count: Cell<u64>,
}
impl Accumulator {
pub fn add(&self, since: Instant) {
self.total.set(self.total.get() + since.elapsed());
self.count.set(self.count.get() + 1);
}
pub fn report(&self, label: &str) {
if enabled() {
eprintln!(
"[timing] {:>9.3} ms total in {label} ({} calls)",
self.total.get().as_secs_f64() * 1e3,
self.count.get()
);
}
}
}
thread_local! {
pub static LUA: Accumulator = Accumulator::default();
pub static FONTS: Accumulator = Accumulator::default();
}