Skip to main content

rypipe_core/
profiling.rs

1//! Named stage timings for the execution engine.
2//!
3//! Disabled by default. When disabled, every call is one relaxed atomic load
4//! and a branch; when enabled, each stage accumulates nanoseconds across all
5//! workers so adapter authors can see where a read spends its time (split,
6//! validate, parse/build, export, merge) without a system profiler.
7
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
10/// Stage slots, in report order.
11pub const SPLIT: usize = 0;
12pub const VALIDATE: usize = 1;
13pub const PARSE: usize = 2;
14pub const EXPORT: usize = 3;
15pub const MERGE: usize = 4;
16/// Number of stages.
17pub const COUNT: usize = 5;
18
19/// Human-readable names, index-aligned with the stage constants.
20pub const NAMES: [&str; COUNT] = ["split", "validate", "parse", "export", "merge"];
21
22static ENABLED: AtomicBool = AtomicBool::new(false);
23static NANOS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
24static CALLS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
25
26/// Whether stage timing is currently on.
27#[inline]
28pub fn enabled() -> bool {
29    ENABLED.load(Ordering::Relaxed)
30}
31
32/// Clear all counters and start accounting.
33pub fn reset() {
34    for i in 0..COUNT {
35        NANOS[i].store(0, Ordering::Relaxed);
36        CALLS[i].store(0, Ordering::Relaxed);
37    }
38    ENABLED.store(true, Ordering::Relaxed);
39}
40
41/// Stop accounting (counters keep their last values).
42pub fn disable() {
43    ENABLED.store(false, Ordering::Relaxed);
44}
45
46/// Add `nanos` to a stage. No-op unless enabled.
47#[inline]
48pub fn add(stage: usize, nanos: u64) {
49    if enabled() {
50        NANOS[stage].fetch_add(nanos, Ordering::Relaxed);
51        CALLS[stage].fetch_add(1, Ordering::Relaxed);
52    }
53}
54
55/// `(stage_name, total_nanos, calls)` for every stage.
56pub fn snapshot() -> Vec<(&'static str, u64, u64)> {
57    (0..COUNT)
58        .map(|i| {
59            (
60                NAMES[i],
61                NANOS[i].load(Ordering::Relaxed),
62                CALLS[i].load(Ordering::Relaxed),
63            )
64        })
65        .collect()
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn counters_accumulate_only_while_enabled() {
74        disable();
75        add(PARSE, 100);
76        assert_eq!(snapshot()[PARSE].1, 0, "no accounting while disabled");
77
78        reset();
79        add(PARSE, 5);
80        add(PARSE, 7);
81        let s = snapshot();
82        assert_eq!(s[PARSE].1, 12);
83        assert_eq!(s[PARSE].2, 2);
84        assert_eq!(s[SPLIT].1, 0);
85        disable();
86    }
87}