brep_geometry/instrument/
blend_timing.rs1use std::cell::{Cell, RefCell};
4use web_time::Instant;
5
6#[derive(Clone, Debug, PartialEq)]
9pub struct BlendTiming {
10 pub measure: String,
11 pub ms: f64,
12 pub count: u64,
13}
14
15thread_local! {
16 static CAPTURE: Cell<bool> = const { Cell::new(false) };
17 static ENABLED: Cell<bool> = const { Cell::new(false) };
18 static TO_STDERR: Cell<bool> = const { Cell::new(false) };
19 static LEDGER: RefCell<Vec<BlendTiming>> = const { RefCell::new(Vec::new()) };
20}
21
22pub fn blend_timing_capture(on: bool) {
25 CAPTURE.with(|capture| capture.set(on));
26}
27
28pub fn take_blend_timings() -> Vec<BlendTiming> {
31 let mut entries = LEDGER.with(|ledger| std::mem::take(&mut *ledger.borrow_mut()));
32 entries.sort_by(|a, b| a.measure.cmp(&b.measure));
33 entries
34}
35
36pub fn enabled() -> bool {
38 ENABLED.with(|enabled| enabled.get())
39}
40
41pub fn begin_operation() {
42 let profile = crate::profile::profile_enabled();
43 TO_STDERR.with(|to_stderr| to_stderr.set(profile));
44 let on = profile || CAPTURE.with(|capture| capture.get());
45 ENABLED.with(|enabled| enabled.set(on));
46 if on {
47 LEDGER.with(|ledger| ledger.borrow_mut().clear());
48 }
49}
50
51pub fn end_operation() {
52 if TO_STDERR.with(|to_stderr| to_stderr.get()) {
53 let mut entries = LEDGER.with(|ledger| ledger.borrow().clone());
54 entries.sort_by(|a, b| a.measure.cmp(&b.measure));
55 for entry in entries {
56 if entry.measure.starts_with("timing.") {
57 eprintln!("blend.{}={:.3} n={}", entry.measure, entry.ms, entry.count);
58 } else {
59 eprintln!("blend.{}={}", entry.measure, entry.count);
60 }
61 }
62 }
63 ENABLED.with(|enabled| enabled.set(false));
64}
65
66fn add(measure: &str, ms: f64, count: u64) {
67 LEDGER.with(|ledger| {
68 let mut ledger = ledger.borrow_mut();
69 match ledger.iter_mut().find(|entry| entry.measure == measure) {
70 Some(entry) => {
71 entry.ms += ms;
72 entry.count += count;
73 }
74 None => ledger.push(BlendTiming { measure: measure.to_string(), ms, count }),
75 }
76 });
77}
78
79pub fn record_ms(measure: &str, ms: f64) {
81 if enabled() {
82 add(measure, ms, 1);
83 }
84}
85
86pub fn record_count(measure: &str, n: u64) {
88 if enabled() {
89 add(measure, 0.0, n);
90 }
91}
92
93pub struct BlendTimer {
96 measure: &'static str,
97 started: Option<Instant>,
98}
99
100impl BlendTimer {
101 pub fn start(measure: &'static str) -> BlendTimer {
102 BlendTimer { measure, started: enabled().then(Instant::now) }
103 }
104
105 pub fn elapsed_ms(&self) -> f64 {
107 self.started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1_000.0)
108 }
109
110 pub fn stop(mut self) -> f64 {
112 let ms = self.elapsed_ms();
113 if self.started.take().is_some() {
114 add(self.measure, ms, 1);
115 }
116 ms
117 }
118}
119
120impl Drop for BlendTimer {
121 fn drop(&mut self) {
122 if let Some(started) = self.started.take() {
123 add(self.measure, started.elapsed().as_secs_f64() * 1_000.0, 1);
124 }
125 }
126}