OXYGENHUB
# 8457a6cc6984 oxygen / crates / oxy-core / src / timing.rs
1.2 KiB · Rust · last changed Faster state loading: seeded fast hashing for the file graphs, no unused predecessor map, inline successor sets, lines moved rather than copied; OXY_TIMINGS=1 prints snapshot phase timings. Clean status at 10 000 files 0.96 s to 0.52 s, memory 657 to 239 MB 1 month ago source blame history raw
1
//! Opt-in phase timings (`OXY_TIMINGS=1`): each named phase prints its
2
//! duration to stderr, for measuring where a command spends its time
3
//! without a profiler.
4
5
use std::sync::OnceLock;
6
use std::time::Instant;
7
8
fn enabled() -> bool {
9
    static ON: OnceLock<bool> = OnceLock::new();
10
    *ON.get_or_init(|| std::env::var_os("OXY_TIMINGS").is_some_and(|v| !v.is_empty() && v != "0"))
11
}
12
13
/// Report a duration measured by hand (several intervals summed), if timings are on.
14
pub fn record(name: &str, d: std::time::Duration) {
15
    if enabled() {
16
        eprintln!("timing {:<28} {:>9.2} ms", name, d.as_secs_f64() * 1000.0);
17
    }
18
}
19
20
/// Prints `timing <name> <ms>` when dropped, if timings are on.
21
pub struct Phase {
22
    name: &'static str,
23
    started: Option<Instant>,
24
}
25
26
/// Start timing a phase; the guard reports when it goes out of scope.
27
pub fn phase(name: &'static str) -> Phase {
28
    Phase {
29
        name,
30
        started: enabled().then(Instant::now),
31
    }
32
}
33
34
impl Drop for Phase {
35
    fn drop(&mut self) {
36
        if let Some(t) = self.started {
37
            eprintln!(
38
                "timing {:<28} {:>9.2} ms",
39
                self.name,
40
                t.elapsed().as_secs_f64() * 1000.0
41
            );
42
        }
43
    }
44
}