Here is a Rust module. ``` //! Operator profile of the Original serve path's host phases (`LELEKA_SERVE_PROFILE=1`, off by default). //! //! Named wall-clock spans (inclusive of any wait inside them) are summed per thread and printed as one //! `DBG profile` line per request by the stack, then reset. Nested spans are not additive. Nothing here //! changes what runs: when the switch is off a span is one cached boolean test. use std::cell::RefCell; use std::time::Instant; /// `LELEKA_SERVE_PROFILE` set to anything but `0`, read once. pub(crate) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("LELEKA_SERVE_PROFILE").is_ok_and(|v| !v.is_empty() && v != "0")) } thread_local! { static SUMS: RefCell> = const { RefCell::new(Vec::new()) }; } /// A running span; its time is added to `name` when it is dropped. pub(crate) struct Span { name: &'static str, started: Option, } impl Span { /// Add the time so far to this span's name and disarm it. pub(crate) fn stop(&mut self) { if let Some(started) = self.started.take() { add(self.name, started.elapsed().as_secs_f64() * 1e3); } } } impl Drop for Span { fn drop(&mut self) { if let Some(started) = self.started { add(self.name, started.elapsed().as_secs_f64() * 1e3); } } } /// Start a span (a no-op unless the profile is on). pub(crate) fn span(name: &'static str) -> Span { Span { name, started: enabled().then(Instant::now) } } /// Add `ms` to `name` (one call). pub(crate) fn add(name: &'static str, ms: f64) { if !enabled() { return; } SUMS.with(|sums| { let mut sums = sums.borrow_mut(); match sums.iter_mut().find(|(n, _, _)| *n == name) { Some(entry) => { entry.1 += ms; entry.2 += 1; } None => sums.push((name, ms, 1)), } }); } /// Print the sums since the last report as `DBG profile