Skip to main content

kh_loader/
load_timing.rs

1//! Opt-in load-path phase timings (`KAKEHASHI_LOAD_TIMING`).
2//!
3//! Roadmap2-style: **default off**. Hot path when off is one atomic mode load
4//! per phase start/end. When on, records wall `Instant` deltas and dumps to
5//! stderr before guest entry (and again on host-side return if any).
6//!
7//! Values: unset/`0`/`off` = off; `1`/`on`/`true` = on.
8
9use std::fmt::Write as _;
10use std::io::{self, Write as IoWrite};
11use std::sync::Mutex;
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::time::Instant;
14
15const MODE_UNINIT: u8 = 0;
16const MODE_OFF: u8 = 1;
17const MODE_ON: u8 = 2;
18
19static MODE: AtomicU8 = AtomicU8::new(MODE_UNINIT);
20
21struct State {
22    run_start: Option<Instant>,
23    phases: Vec<(&'static str, u64)>,
24    /// Extra one-line notes (image counts, etc.).
25    notes: Vec<String>,
26}
27
28static STATE: Mutex<Option<State>> = Mutex::new(None);
29
30fn mode_from_env() -> u8 {
31    match std::env::var_os("KAKEHASHI_LOAD_TIMING") {
32        None => MODE_OFF,
33        Some(v) => {
34            if v == "0"
35                || v.eq_ignore_ascii_case("false")
36                || v.eq_ignore_ascii_case("no")
37                || v.eq_ignore_ascii_case("off")
38            {
39                MODE_OFF
40            } else {
41                MODE_ON
42            }
43        }
44    }
45}
46
47#[inline]
48fn resolved_mode() -> u8 {
49    let m = MODE.load(Ordering::Relaxed);
50    if m != MODE_UNINIT {
51        return m;
52    }
53    let parsed = mode_from_env();
54    let _ = MODE.compare_exchange(MODE_UNINIT, parsed, Ordering::Relaxed, Ordering::Relaxed);
55    MODE.load(Ordering::Relaxed)
56}
57
58/// Whether load timing is enabled (after first resolve).
59#[inline]
60#[must_use]
61pub fn enabled() -> bool {
62    resolved_mode() == MODE_ON
63}
64
65/// Start a new timed run (clears previous phases). No-op when off.
66pub fn begin_run() {
67    if !enabled() {
68        return;
69    }
70    if let Ok(mut g) = STATE.lock() {
71        *g = Some(State {
72            run_start: Some(Instant::now()),
73            phases: Vec::with_capacity(16),
74            notes: Vec::new(),
75        });
76    }
77}
78
79/// Record a completed phase duration in nanoseconds.
80pub fn record(name: &'static str, ns: u64) {
81    if !enabled() {
82        return;
83    }
84    if let Ok(mut g) = STATE.lock()
85        && let Some(st) = g.as_mut()
86    {
87        st.phases.push((name, ns));
88    }
89}
90
91/// Time a closure and record it under `name`.
92#[inline]
93pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
94    if !enabled() {
95        return f();
96    }
97    let t0 = Instant::now();
98    let out = f();
99    let ns = u64::try_from(t0.elapsed().as_nanos()).unwrap_or(u64::MAX);
100    record(name, ns);
101    out
102}
103
104/// Time a fallible closure.
105#[inline]
106pub fn time_result<T, E>(name: &'static str, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
107    if !enabled() {
108        return f();
109    }
110    let t0 = Instant::now();
111    let out = f();
112    let ns = u64::try_from(t0.elapsed().as_nanos()).unwrap_or(u64::MAX);
113    record(name, ns);
114    out
115}
116
117/// Attach a free-form note (image counts, paths, …).
118pub fn note(msg: impl Into<String>) {
119    if !enabled() {
120        return;
121    }
122    if let Ok(mut g) = STATE.lock()
123        && let Some(st) = g.as_mut()
124    {
125        st.notes.push(msg.into());
126    }
127}
128
129#[allow(clippy::integer_division, clippy::arithmetic_side_effects)]
130fn ns_to_ms_tenths(ns: u64) -> (u64, u64) {
131    // ms and tenths: ns / 1_000_000, (ns % 1_000_000) / 100_000
132    let ms = ns / 1_000_000;
133    let tenths = (ns % 1_000_000) / 100_000;
134    (ms, tenths)
135}
136
137#[allow(clippy::integer_division, clippy::arithmetic_side_effects)]
138fn pct_tenths(part: u64, whole: u64) -> (u64, u64) {
139    if whole == 0 {
140        return (0, 0);
141    }
142    // 1000 * part / whole → whole% * 10
143    let x = part.saturating_mul(1000) / whole;
144    (x / 10, x % 10)
145}
146
147/// Dump phase table to stderr. Safe before guest entry / after guest return.
148pub fn dump(label: &str) {
149    if !enabled() {
150        return;
151    }
152    let Ok(g) = STATE.lock() else {
153        return;
154    };
155    let Some(st) = g.as_ref() else {
156        return;
157    };
158    let total_ns = st.run_start.map_or(0, |t| {
159        u64::try_from(t.elapsed().as_nanos()).unwrap_or(u64::MAX)
160    });
161    let sum_phases: u64 = st.phases.iter().map(|(_, ns)| *ns).sum();
162    let (tw, tt) = ns_to_ms_tenths(total_ns);
163    let (sw, stt) = ns_to_ms_tenths(sum_phases);
164    let mut out = format!(
165        "kh load timing ({label}): wall_ms={tw}.{tt}  sum_phases_ms={sw}.{stt}  phases={}\n",
166        st.phases.len()
167    );
168    for (i, (name, ns)) in st.phases.iter().enumerate() {
169        let (ms, tenths) = ns_to_ms_tenths(*ns);
170        let (pw, pt) = pct_tenths(*ns, total_ns);
171        let rank = i.saturating_add(1);
172        let _ = writeln!(
173            out,
174            "  {rank:>2}  {ms:>5}.{tenths} ms  {pw:>3}.{pt}%  {name}"
175        );
176    }
177    let unaccounted = total_ns.saturating_sub(sum_phases);
178    if unaccounted > 0 {
179        let (ms, tenths) = ns_to_ms_tenths(unaccounted);
180        let (pw, pt) = pct_tenths(unaccounted, total_ns);
181        let _ = writeln!(
182            out,
183            "       {ms:>5}.{tenths} ms  {pw:>3}.{pt}%  (unaccounted)"
184        );
185    }
186    for n in &st.notes {
187        out.push_str("  note: ");
188        out.push_str(n);
189        out.push('\n');
190    }
191    drop(io::stderr().write_all(out.as_bytes())); // IoWrite
192}