Skip to main content

semi_persistent_egraph/
phase_timing.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Per-phase wall-clock accounting for the saturation round loop.
4//!
5//! The round loop's cost splits into rebuild, index build, and matching, and the
6//! index build splits again into the walk that writes each family's `(key,
7//! value)` stream and the container build that turns a stream into a span table.
8//! Attributing a regression to one of those needs the split measured in process,
9//! not inferred from differences of end-to-end wall times: the E6 cycle costs
10//! ~180 ms against a base build of ~750 ms, so a 10 ms phase is inside the noise
11//! of any subtraction the runner can do from outside.
12//!
13//! Off by default and zero cost when off. The `phase-timing` feature selects the
14//! recording implementation; without it every entry point below is an empty
15//! inline function and the call sites compile away. With it, `EGRAPH_PHASE=1`
16//! prints the totals at exit and `EGRAPH_PHASE=rounds` additionally prints one
17//! line per round.
18//!
19//! Call sites stay unconditional so the instrumented and uninstrumented builds
20//! are the same source; see `saturate.rs` and `index.rs`.
21
22/// Slot names, in report order. Indented names are sub-phases of the entry above
23/// them and are already included in it, so a column of totals double-counts on
24/// purpose: the parent is the number the round loop pays and the children say
25/// where it went.
26pub const SLOTS: &[&str] = &[
27    "rebuild",
28    "index.full",
29    "  full.walk",
30    "  full.span.by_op",
31    "  full.span.by_repr",
32    "  full.span.by_child_pos",
33    "  full.span.by_contains",
34    "  full.fanouts",
35    "index.delta",
36    "  delta.sort+dedup",
37    "  delta.walk",
38    "  delta.span.by_op",
39    "  delta.span.by_repr",
40    "  delta.span.by_child_pos",
41    "  delta.span.by_contains",
42    "match+apply",
43    "  stats",
44];
45
46pub const REBUILD: usize = 0;
47pub const FULL: usize = 1;
48pub const FULL_WALK: usize = 2;
49pub const FULL_SPAN_OP: usize = 3;
50pub const FULL_SPAN_REPR: usize = 4;
51pub const FULL_SPAN_CHILD_POS: usize = 5;
52pub const FULL_SPAN_CONTAINS: usize = 6;
53pub const FULL_FANOUTS: usize = 7;
54pub const DELTA: usize = 8;
55pub const DELTA_DEDUP: usize = 9;
56pub const DELTA_WALK: usize = 10;
57pub const DELTA_SPAN_OP: usize = 11;
58pub const DELTA_SPAN_REPR: usize = 12;
59pub const DELTA_SPAN_CHILD_POS: usize = 13;
60pub const DELTA_SPAN_CONTAINS: usize = 14;
61pub const MATCH: usize = 15;
62pub const STATS: usize = 16;
63
64/// Scalar counters, summed over the run. The key/value pairs are the whole
65/// question the diagnosis asks: a dense span table costs one `Span` per key
66/// whether or not the key occurs, so `keys` far above `values` is the term to
67/// remove.
68pub const COUNTERS: &[&str] = &[
69    "rounds",
70    "rounds.with_delta",
71    "variants",
72    "full.nodes",
73    "full.by_child_pos.keys",
74    "full.by_child_pos.values",
75    "full.by_child_pos.nonempty",
76    "delta.ids",
77    "delta.by_child_pos.keys",
78    "delta.by_child_pos.values",
79    "delta.by_child_pos.nonempty",
80];
81
82pub const C_ROUNDS: usize = 0;
83pub const C_ROUNDS_DELTA: usize = 1;
84pub const C_VARIANTS: usize = 2;
85pub const C_FULL_NODES: usize = 3;
86pub const C_FULL_CP_KEYS: usize = 4;
87pub const C_FULL_CP_VALUES: usize = 5;
88pub const C_FULL_CP_NONEMPTY: usize = 6;
89pub const C_DELTA_IDS: usize = 7;
90pub const C_DELTA_CP_KEYS: usize = 8;
91pub const C_DELTA_CP_VALUES: usize = 9;
92pub const C_DELTA_CP_NONEMPTY: usize = 10;
93
94#[cfg(not(feature = "phase-timing"))]
95mod imp {
96    /// Zero-cost stand-in: no field, no `Drop`, so the guard and its scope
97    /// vanish in the uninstrumented build.
98    pub struct Timer;
99
100    impl Timer {
101        #[inline(always)]
102        pub fn start(_slot: usize) -> Self {
103            Timer
104        }
105
106        /// End the timed scope early. `drop` would do it, but only in the
107        /// recording build does this type implement `Drop`, and clippy reads
108        /// `drop` on a type without one as a mistake.
109        #[inline(always)]
110        pub fn stop(self) {}
111    }
112
113    #[inline(always)]
114    pub fn count(_c: usize, _v: u64) {}
115    #[inline(always)]
116    pub fn round_line(_tag: &str) {}
117    #[inline(always)]
118    pub fn dump() {}
119    #[inline(always)]
120    pub fn enabled() -> bool {
121        false
122    }
123}
124
125#[cfg(feature = "phase-timing")]
126mod imp {
127    use std::sync::atomic::{AtomicU64, Ordering};
128    use std::sync::{Mutex, OnceLock};
129    use std::time::Instant;
130
131    const N: usize = super::SLOTS.len();
132    const M: usize = super::COUNTERS.len();
133
134    // `AtomicU64` rather than a thread-local `Cell`: the engine is
135    // single-threaded, so this is uncontended and the relaxed add is a plain
136    // instruction, and a `static` needs no lazy initialization on the hot path.
137    static NANOS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N];
138    static CALLS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N];
139    static COUNTS: [AtomicU64; M] = [const { AtomicU64::new(0) }; M];
140
141    fn mode() -> &'static str {
142        static MODE: OnceLock<String> = OnceLock::new();
143        MODE.get_or_init(|| std::env::var("EGRAPH_PHASE").unwrap_or_default())
144    }
145
146    pub fn enabled() -> bool {
147        !mode().is_empty()
148    }
149
150    fn per_round() -> bool {
151        mode() == "rounds"
152    }
153
154    pub struct Timer {
155        slot: usize,
156        t0: Instant,
157    }
158
159    impl Timer {
160        #[inline]
161        pub fn start(slot: usize) -> Self {
162            Timer {
163                slot,
164                t0: Instant::now(),
165            }
166        }
167
168        /// End the timed scope early; see the stand-in's `stop`.
169        #[inline]
170        pub fn stop(self) {}
171    }
172
173    impl Drop for Timer {
174        #[inline]
175        fn drop(&mut self) {
176            let ns = self.t0.elapsed().as_nanos() as u64;
177            NANOS[self.slot].fetch_add(ns, Ordering::Relaxed);
178            CALLS[self.slot].fetch_add(1, Ordering::Relaxed);
179        }
180    }
181
182    #[inline]
183    pub fn count(c: usize, v: u64) {
184        COUNTS[c].fetch_add(v, Ordering::Relaxed);
185    }
186
187    fn last() -> &'static Mutex<([u64; N], [u64; M], usize)> {
188        static LAST: OnceLock<Mutex<([u64; N], [u64; M], usize)>> = OnceLock::new();
189        LAST.get_or_init(|| Mutex::new(([0; N], [0; M], 0)))
190    }
191
192    /// One line per round, in milliseconds, of what accumulated since the
193    /// previous call. Printed only under `EGRAPH_PHASE=rounds`.
194    pub fn round_line(tag: &str) {
195        if !per_round() {
196            return;
197        }
198        let mut g = last().lock().unwrap();
199        let (prev, prev_c, seq) = &mut *g;
200        let mut cells = String::new();
201        for i in 0..N {
202            let now = NANOS[i].load(Ordering::Relaxed);
203            cells.push_str(&format!("\t{:.3}", (now - prev[i]) as f64 / 1e6));
204            prev[i] = now;
205        }
206        for i in 0..M {
207            let now = COUNTS[i].load(Ordering::Relaxed);
208            cells.push_str(&format!("\t{}", now - prev_c[i]));
209            prev_c[i] = now;
210        }
211        if *seq == 0 {
212            let mut hdr = String::from("PHASE_ROUND\tseq\ttag");
213            for s in super::SLOTS {
214                hdr.push('\t');
215                hdr.push_str(s.trim());
216            }
217            for s in super::COUNTERS {
218                hdr.push('\t');
219                hdr.push_str(s);
220            }
221            eprintln!("{hdr}");
222        }
223        eprintln!("PHASE_ROUND\t{seq}\t{tag}{cells}");
224        *seq += 1;
225    }
226
227    pub fn dump() {
228        if !enabled() {
229            return;
230        }
231        eprintln!("\n=== phase totals ===");
232        eprintln!(
233            "{:<26} {:>12} {:>10} {:>12}",
234            "phase", "ms", "calls", "us/call"
235        );
236        for i in 0..N {
237            let ns = NANOS[i].load(Ordering::Relaxed);
238            let c = CALLS[i].load(Ordering::Relaxed);
239            if c == 0 {
240                continue;
241            }
242            eprintln!(
243                "{:<26} {:>12.3} {:>10} {:>12.3}",
244                super::SLOTS[i],
245                ns as f64 / 1e6,
246                c,
247                ns as f64 / 1e3 / c as f64
248            );
249        }
250        eprintln!("--- counters ---");
251        for i in 0..M {
252            let v = COUNTS[i].load(Ordering::Relaxed);
253            if v == 0 {
254                continue;
255            }
256            eprintln!("{:<26} {:>12}", super::COUNTERS[i], v);
257        }
258    }
259}
260
261pub use imp::{Timer, count, dump, enabled, round_line};