Skip to main content

vizia_core/
profiling.rs

1//! A lightweight profiler for the vizia update and draw pipeline.
2//!
3//! Enable the `profiling` feature to compile it in. Without the feature every function here is a
4//! no-op, so the instrumentation in the systems costs nothing.
5//!
6//! Each system opens a [`Scope`] while it runs, which records how long the system took. Recording
7//! only happens between [`start_capture`] and [`stop_capture`].
8//! The returned [`Capture`] implements [`Display`](std::fmt::Display).
9//!
10//! ```ignore
11//! vizia::profiling::start_capture();
12//! // ... trigger a state change and let the event loop process it ...
13//! let capture = vizia::profiling::stop_capture();
14//! println!("{capture}");
15//! ```
16
17use std::fmt;
18use std::time::Duration;
19
20/// Whether the profiler is compiled in (the `profiling` feature is enabled).
21pub const ENABLED: bool = cfg!(feature = "profiling");
22
23/// A single recorded scope.
24#[derive(Debug, Clone)]
25pub struct ScopeRecord {
26    /// The name of the scope, usually the name of the system.
27    pub name: &'static str,
28    /// Nesting depth. Top-level passes (`update`, `draw`) have a depth of zero.
29    pub depth: usize,
30    /// Wall-clock time spent in the scope, including nested scopes.
31    pub duration: Duration,
32}
33
34/// The scopes recorded between [`start_capture`] and [`stop_capture`], in the order they started.
35#[derive(Debug, Clone, Default)]
36pub struct Capture {
37    pub records: Vec<ScopeRecord>,
38}
39
40impl fmt::Display for Capture {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        if !ENABLED {
43            return writeln!(f, "vizia profiling is disabled; enable the `profiling` feature.");
44        }
45
46        writeln!(f, "{:<32} {:>10}", "scope", "time (ms)")?;
47        for (index, record) in self.records.iter().enumerate() {
48            if record.depth == 0 && index != 0 {
49                writeln!(f)?;
50            }
51            let name = format!("{}{}", "  ".repeat(record.depth), record.name);
52            writeln!(f, "{:<32} {:>10.3}", name, record.duration.as_secs_f64() * 1000.0)?;
53        }
54        Ok(())
55    }
56}
57
58#[cfg(feature = "profiling")]
59mod imp {
60    use super::{Capture, ScopeRecord};
61    use std::cell::RefCell;
62    use std::time::Instant;
63
64    struct OpenScope {
65        index: usize,
66        start: Instant,
67    }
68
69    #[derive(Default)]
70    struct State {
71        capturing: bool,
72        // Incremented on every start/stop so that guards from a previous capture are ignored.
73        generation: u64,
74        records: Vec<ScopeRecord>,
75        stack: Vec<OpenScope>,
76    }
77
78    thread_local! {
79        static STATE: RefCell<State> = RefCell::default();
80    }
81
82    pub struct Scope {
83        generation: Option<u64>,
84    }
85
86    pub fn scope(name: &'static str) -> Scope {
87        STATE.with_borrow_mut(|state| {
88            if !state.capturing {
89                return Scope { generation: None };
90            }
91            let index = state.records.len();
92            state.records.push(ScopeRecord {
93                name,
94                depth: state.stack.len(),
95                duration: Default::default(),
96            });
97            state.stack.push(OpenScope { index, start: Instant::now() });
98            Scope { generation: Some(state.generation) }
99        })
100    }
101
102    fn close(state: &mut State, open: OpenScope, now: Instant) {
103        state.records[open.index].duration = now - open.start;
104    }
105
106    impl Drop for Scope {
107        fn drop(&mut self) {
108            let Some(generation) = self.generation else { return };
109            let now = Instant::now();
110            let _ = STATE.try_with(|state| {
111                let mut state = state.borrow_mut();
112                if state.generation != generation {
113                    return;
114                }
115                if let Some(open) = state.stack.pop() {
116                    close(&mut state, open, now);
117                }
118            });
119        }
120    }
121
122    pub fn start_capture() {
123        STATE.with_borrow_mut(|state| {
124            state.capturing = true;
125            state.generation += 1;
126            state.records.clear();
127            state.stack.clear();
128        });
129    }
130
131    pub fn stop_capture() -> Capture {
132        let now = Instant::now();
133        STATE.with_borrow_mut(|state| {
134            // Close any scopes that are still open so their records are usable.
135            while let Some(open) = state.stack.pop() {
136                close(state, open, now);
137            }
138            state.capturing = false;
139            state.generation += 1;
140            Capture { records: std::mem::take(&mut state.records) }
141        })
142    }
143
144    pub fn is_capturing() -> bool {
145        STATE.with_borrow(|state| state.capturing)
146    }
147}
148
149#[cfg(not(feature = "profiling"))]
150mod imp {
151    use super::Capture;
152
153    pub struct Scope;
154
155    #[inline(always)]
156    pub fn scope(_name: &'static str) -> Scope {
157        Scope
158    }
159
160    pub fn start_capture() {}
161
162    pub fn stop_capture() -> Capture {
163        Capture::default()
164    }
165
166    pub fn is_capturing() -> bool {
167        false
168    }
169}
170
171/// RAII guard returned by [`scope`]. The scope ends when the guard is dropped.
172#[must_use = "the scope ends as soon as the guard is dropped"]
173pub struct Scope(#[allow(dead_code)] imp::Scope);
174
175/// Opens a profiling scope which lasts until the returned guard is dropped.
176///
177/// Scopes nest: a scope opened while another is active becomes its child.
178#[inline(always)]
179pub fn scope(name: &'static str) -> Scope {
180    Scope(imp::scope(name))
181}
182
183/// Starts a new capture on the current thread, discarding any previously recorded scopes.
184pub fn start_capture() {
185    imp::start_capture()
186}
187
188/// Stops the current capture and returns everything recorded since [`start_capture`].
189pub fn stop_capture() -> Capture {
190    imp::stop_capture()
191}
192
193/// Returns true if a capture is in progress on the current thread.
194pub fn is_capturing() -> bool {
195    imp::is_capturing()
196}