pub fn span<T>(name: &'static str, work: impl FnOnce() -> T) -> T {
#[cfg(feature = "timing")]
{
recording::span(name, work)
}
#[cfg(not(feature = "timing"))]
{
let _ = name;
work()
}
}
#[cfg(feature = "timing")]
pub use recording::{arm, take};
#[cfg(feature = "timing")]
mod recording {
use std::cell::{Cell, RefCell};
use std::time::{Duration, Instant};
thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
static SPANS: RefCell<Vec<(&'static str, Duration)>> = const { RefCell::new(Vec::new()) };
}
pub fn arm() {
ARMED.with(|armed| armed.set(true));
}
#[must_use]
pub fn take() -> Vec<(&'static str, Duration)> {
SPANS.with(|spans| std::mem::take(&mut *spans.borrow_mut()))
}
pub(super) fn span<T>(name: &'static str, work: impl FnOnce() -> T) -> T {
if !ARMED.with(Cell::get) {
return work();
}
let start = Instant::now();
let value = work();
let elapsed = start.elapsed();
SPANS.with(|spans| spans.borrow_mut().push((name, elapsed)));
value
}
#[cfg(test)]
mod tests {
#[test]
fn records_spans_only_on_an_armed_thread() {
assert_eq!(super::span("before", || 1), 1);
assert_eq!(super::take(), []);
super::arm();
assert_eq!(super::span("work", || 2), 2);
let spans = super::take();
assert_eq!(spans.len(), 1);
assert_eq!(spans.first().map(|s| s.0), Some("work"));
assert_eq!(super::take(), []);
}
}
}