use std::sync::Mutex;
use std::time::{Duration, Instant};
static CURRENT: Mutex<Option<(&'static str, Instant)>> = Mutex::new(None);
#[must_use = "the phase ends when the guard drops"]
pub(crate) fn enter(name: &'static str) -> PhaseGuard {
let started = Instant::now();
let outer = CURRENT
.lock()
.map(|mut slot| slot.replace((name, started)))
.unwrap_or(None);
PhaseGuard {
name,
started,
outer,
}
}
pub(crate) fn current() -> Option<(&'static str, Duration)> {
CURRENT
.lock()
.ok()
.and_then(|slot| slot.map(|(name, started)| (name, started.elapsed())))
}
pub(crate) struct PhaseGuard {
name: &'static str,
started: Instant,
outer: Option<(&'static str, Instant)>,
}
impl Drop for PhaseGuard {
fn drop(&mut self) {
if let Ok(mut slot) = CURRENT.lock() {
*slot = self.outer;
}
if std::env::var_os("LEAN_CTX_PHASE_TIMING").is_some_and(|v| v == "1") {
eprintln!("[phase] {} {:?}", self.name, self.started.elapsed());
}
}
}