Cotton code
45 lines · 1.3 KB · RustRaw
//! Named wall-clock spans, summed per thread: how a measurement says where a//! fresh copy's time goes on a box where `perf` is not allowed. A span costs//! two clock reads; nothing reads the sums but a measurement.use std::cell::RefCell;use std::collections::BTreeMap;use std::time::{Duration, Instant};thread_local! {    static SUMS: RefCell<BTreeMap<&'static str, (Duration, u64)>> = const { RefCell::new(BTreeMap::new()) };}/// Times `name` until it is dropped.pub struct Span {    name: &'static str,    began: Instant,}/// Start the span `name`; its time is added when the answer is dropped.pub fn span(name: &'static str) -> Span {    Span { name, began: Instant::now() }}impl Drop for Span {    fn drop(&mut self) {        let took = self.began.elapsed();        SUMS.with(|sums| {            let mut sums = sums.borrow_mut();            let entry = sums.entry(self.name).or_default();            entry.0 += took;            entry.1 += 1;        });    }}/// This thread's sums since the last take, longest first, and start again.pub fn take() -> Vec<(&'static str, Duration, u64)> {    let mut sums: Vec<_> = SUMS.with(|sums| std::mem::take(&mut *sums.borrow_mut()))        .into_iter()        .map(|(name, (took, count))| (name, took, count))        .collect();    sums.sort_by(|a, b| b.1.cmp(&a.1));    sums}