1use std::fmt;
18use std::time::Duration;
19
20pub const ENABLED: bool = cfg!(feature = "profiling");
22
23#[derive(Debug, Clone)]
25pub struct ScopeRecord {
26 pub name: &'static str,
28 pub depth: usize,
30 pub duration: Duration,
32}
33
34#[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 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 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#[must_use = "the scope ends as soon as the guard is dropped"]
173pub struct Scope(#[allow(dead_code)] imp::Scope);
174
175#[inline(always)]
179pub fn scope(name: &'static str) -> Scope {
180 Scope(imp::scope(name))
181}
182
183pub fn start_capture() {
185 imp::start_capture()
186}
187
188pub fn stop_capture() -> Capture {
190 imp::stop_capture()
191}
192
193pub fn is_capturing() -> bool {
195 imp::is_capturing()
196}