tilo_actions/
profiling.rs1#[cfg(not(target_arch = "wasm32"))]
15pub use recorder::{Phase, Sample, begin_live, observe, take_live, unobserved};
16
17#[cfg(target_arch = "wasm32")]
19pub struct Phase;
20
21#[cfg(target_arch = "wasm32")]
22impl Phase {
23 #[inline]
25 #[must_use]
26 pub const fn start(_name: &'static str) -> Self {
27 Self
28 }
29
30 #[inline]
32 #[allow(
33 clippy::missing_const_for_fn,
34 reason = "const would stop compiling the moment this Phase gains a destructor, as the recorder's has"
35 )]
36 pub fn end(self) {
37 let Self = self;
38 }
39}
40
41#[cfg(target_arch = "wasm32")]
46#[inline]
47pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
48 operation()
49}
50
51#[cfg(target_arch = "wasm32")]
53#[derive(Debug)]
54pub struct Sample {
55 pub phase: &'static str,
57 pub elapsed_ns: u128,
59 pub calls: usize,
61}
62
63#[cfg(target_arch = "wasm32")]
66#[inline]
67pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
68 (operation(), Vec::new())
69}
70
71#[cfg(target_arch = "wasm32")]
74#[inline]
75pub const fn begin_live() -> bool {
76 false
77}
78
79#[cfg(target_arch = "wasm32")]
82#[inline]
83pub fn take_live() -> Vec<Sample> {
84 Vec::new()
85}
86
87#[inline]
89pub fn measure<T>(phase: &'static str, operation: impl FnOnce() -> T) -> T {
90 let _scope = Phase::start(phase);
91 operation()
92}
93
94#[cfg(not(target_arch = "wasm32"))]
95mod recorder {
96 use std::cell::RefCell;
97 use tilo_clock::time::Instant;
98
99 thread_local! {
100 static RECORDS: RefCell<Option<Capture>> = const { RefCell::new(None) };
101 }
102
103 pub(super) const MAX_PHASES: usize = 64;
105
106 #[derive(Default)]
107 struct Capture {
108 rows: Vec<Sample>,
109 overflow: bool,
110 }
111
112 #[derive(Debug, serde::Serialize)]
115 pub struct Sample {
116 pub phase: &'static str,
118 pub elapsed_ns: u128,
120 pub calls: usize,
122 }
123
124 #[must_use]
126 pub struct Phase(Option<(&'static str, Instant)>);
127
128 impl Phase {
129 pub fn start(name: &'static str) -> Self {
131 Self(
132 RECORDS
133 .with(|records| records.borrow().as_ref().map(|_| (name, tilo_clock::now()))),
134 )
135 }
136
137 pub fn end(self) {
139 drop(self);
140 }
141 }
142
143 impl Drop for Phase {
144 fn drop(&mut self) {
145 let Some((name, start)) = self.0 else {
146 return;
147 };
148 RECORDS.with(|records| {
149 let mut records = records.borrow_mut();
150 let Some(capture) = records.as_mut() else {
151 return;
152 };
153 let elapsed_ns = tilo_clock::now().duration_since(start).as_nanos();
154 if let Some(row) = capture.rows.iter_mut().find(|row| row.phase == name) {
155 match (
156 row.elapsed_ns.checked_add(elapsed_ns),
157 row.calls.checked_add(1),
158 ) {
159 (Some(elapsed), Some(calls)) => {
160 row.elapsed_ns = elapsed;
161 row.calls = calls;
162 }
163 _ => capture.overflow = true,
164 }
165 } else if capture.rows.len() < MAX_PHASES {
166 capture.rows.push(Sample {
167 phase: name,
168 elapsed_ns,
169 calls: 1,
170 });
171 } else {
172 capture.overflow = true;
173 }
174 });
175 }
176 }
177
178 struct Recording;
179
180 impl Drop for Recording {
181 fn drop(&mut self) {
182 RECORDS.with(|records| *records.borrow_mut() = None);
183 }
184 }
185
186 pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
189 struct Resume(Option<Capture>);
190 impl Drop for Resume {
191 fn drop(&mut self) {
192 let capture = self.0.take();
193 RECORDS.with(|records| *records.borrow_mut() = capture);
194 }
195 }
196 let _resume = Resume(RECORDS.with(RefCell::take));
197 operation()
198 }
199
200 pub fn begin_live() -> bool {
206 RECORDS.with(|records| {
207 let mut records = records.borrow_mut();
208 if records.is_some() {
209 return false;
210 }
211 *records = Some(Capture::default());
212 true
213 })
214 }
215
216 pub fn take_live() -> Vec<Sample> {
219 RECORDS
220 .with(RefCell::take)
221 .map(|capture| capture.rows)
222 .unwrap_or_default()
223 }
224
225 pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
227 RECORDS.with(|records| {
228 let mut records = records.borrow_mut();
229 assert!(records.is_none(), "a phase observation is already active");
230 *records = Some(Capture::default());
231 });
232 let recording = Recording;
233 let result = operation();
234 let captured = RECORDS.with(RefCell::take);
235 assert!(captured.is_some(), "phase observation lost its recorder");
236 let capture = captured.unwrap_or_default();
237 drop(recording);
238 assert!(!capture.overflow, "phase observation exceeded its bound");
239 (result, capture.rows)
240 }
241}
242
243#[cfg(all(test, not(target_arch = "wasm32")))]
244mod tests {
245 use super::recorder::MAX_PHASES;
246 use super::{Phase, begin_live, measure, observe, take_live, unobserved};
247
248 tilo_test_env::scenario! {
249 fn an_observation_records_the_scopes_that_run_inside_it;
250
251 phase recording_is_opt_in_and_aggregates_nested_scopes_by_name;
252 {
253 drop(Phase::start("unobserved"));
254 let (value, samples) = observe(|| {
255 let _outer = Phase::start("outer");
256 drop(Phase::start("inner"));
257 measure("inner", || 42)
258 });
259 assert_eq!(value, 42);
260 let calls: Vec<_> = samples
261 .iter()
262 .map(|sample| (sample.phase, sample.calls))
263 .collect();
264 assert_eq!(calls, [("inner", 2), ("outer", 1)]);
265 assert!(observe(|| ()).1.is_empty());
266 }
267
268 phase unobserved_scopes_are_left_out_and_the_observation_resumes;
269 {
270 let ((), samples) = observe(|| {
271 drop(Phase::start("before"));
272 unobserved(|| measure("hidden", || ()));
273 drop(Phase::start("after"));
274 });
275 let names: Vec<_> = samples.iter().map(|sample| sample.phase).collect();
276 assert_eq!(names, ["before", "after"]);
277 unobserved(|| drop(Phase::start("alone")));
279 assert!(observe(|| ()).1.is_empty());
280 }
281
282 phase a_live_observation_spans_calls_until_taken;
283 {
284 drop(Phase::start("before"));
285 begin_live();
286 drop(Phase::start("key"));
287 measure("frame", || drop(Phase::start("key")));
288 let calls: Vec<_> = take_live()
289 .iter()
290 .map(|sample| (sample.phase, sample.calls))
291 .collect();
292 assert_eq!(calls, [("key", 2), ("frame", 1)]);
293 assert!(take_live().is_empty(), "taking it ended it");
294 assert!(observe(|| ()).1.is_empty());
295 }
296 }
297
298 #[test]
299 fn recording_recovers_after_a_nested_observation_panics() {
300 let result = std::panic::catch_unwind(|| observe(|| observe(|| ())));
301 assert!(result.is_err());
302 assert!(observe(|| ()).1.is_empty());
303 }
304
305 #[test]
306 fn recording_refuses_incomplete_coverage_and_retires_its_recorder() {
307 let result = std::panic::catch_unwind(|| {
308 observe(|| {
309 for index in 0..=MAX_PHASES {
310 let name: &'static str = Box::leak(format!("phase-{index}").into_boxed_str());
311 drop(Phase::start(name));
312 }
313 })
314 });
315 assert!(result.is_err());
316 assert!(observe(|| ()).1.is_empty());
317 }
318}