Skip to main content

strata_layout/
prof.rs

1//! Opt-in layout profiling counters gated behind `STRATA_PERF_LOG`.
2//!
3//! The counters accumulate inside one root `compute_layout` invocation and are
4//! printed as a ranked table when the outermost call completes. All entry
5//! points are cheap no-ops unless the environment variable is present.
6
7use std::cell::RefCell;
8
9/// Individual layout work category tracked by the profiler.
10#[derive(Clone, Copy, PartialEq, Eq, Debug)]
11pub enum Slot {
12    Block,
13    Flex,
14    Grid,
15    Table,
16    Inline,
17    Intrinsic,
18    StyleClone,
19    Geometry,
20    Exclusions,
21}
22
23impl Slot {
24    fn index(self) -> usize {
25        match self {
26            Slot::Block => 0,
27            Slot::Flex => 1,
28            Slot::Grid => 2,
29            Slot::Table => 3,
30            Slot::Inline => 4,
31            Slot::Intrinsic => 5,
32            Slot::StyleClone => 6,
33            Slot::Geometry => 7,
34            Slot::Exclusions => 8,
35        }
36    }
37
38    fn label(self) -> &'static str {
39        match self {
40            Slot::Block => "block_layout",
41            Slot::Flex => "flex_solver",
42            Slot::Grid => "grid_solver",
43            Slot::Table => "table_solver",
44            Slot::Inline => "inline_formatting",
45            Slot::Intrinsic => "intrinsic_min_max",
46            Slot::StyleClone => "style_clone",
47            Slot::Geometry => "geometry_apply",
48            Slot::Exclusions => "exclusion_space",
49        }
50    }
51}
52
53const SLOT_COUNT: usize = 9;
54
55#[derive(Clone, Copy, Default)]
56struct Sample {
57    count: u64,
58    nanos: u128,
59}
60
61struct State {
62    enabled: bool,
63    depth: usize,
64    max_depth: usize,
65    max_width: usize,
66    total_nodes: usize,
67    samples: [Sample; SLOT_COUNT],
68}
69
70impl Default for State {
71    fn default() -> Self {
72        Self {
73            enabled: std::env::var_os("STRATA_PERF_LOG").is_some(),
74            depth: 0,
75            max_depth: 0,
76            max_width: 0,
77            total_nodes: 0,
78            samples: [Sample::default(); SLOT_COUNT],
79        }
80    }
81}
82
83struct Frame {
84    slot: Slot,
85    start: std::time::Instant,
86    child_nanos: u128,
87}
88
89thread_local! {
90    static STATE: RefCell<State> = RefCell::new(State::default());
91    static FRAMES: RefCell<Vec<Frame>> = const { RefCell::new(Vec::new()) };
92}
93
94/// Whether layout profiling is enabled.
95pub fn enabled() -> bool {
96    STATE.with(|s| s.borrow().enabled)
97}
98
99/// Marks the beginning of a root layout call. Returns true when this call is
100/// the outermost layout invocation and therefore owns the report lifecycle.
101pub fn enter_layout() -> bool {
102    if !enabled() {
103        return false;
104    }
105    STATE.with(|s| {
106        let mut state = s.borrow_mut();
107        let is_root = state.depth == 0;
108        if is_root {
109            state.samples = [Sample::default(); SLOT_COUNT];
110            state.max_depth = 0;
111            state.max_width = 0;
112            state.total_nodes = 0;
113            FRAMES.with(|frames| frames.borrow_mut().clear());
114        }
115        state.depth += 1;
116        if state.depth > state.max_depth {
117            state.max_depth = state.depth;
118        }
119        is_root
120    })
121}
122
123/// Marks the end of a layout call, printing the ranked report at the root.
124pub fn leave_layout(is_root: bool) {
125    if !enabled() {
126        return;
127    }
128    if is_root {
129        report();
130    }
131    STATE.with(|s| {
132        let mut state = s.borrow_mut();
133        state.depth = state.depth.saturating_sub(1);
134    });
135}
136
137/// Records one child count observation for the widest container report.
138pub fn observe_width(width: usize) {
139    if !enabled() {
140        return;
141    }
142    STATE.with(|s| {
143        let mut state = s.borrow_mut();
144        state.total_nodes += 1;
145        if width > state.max_width {
146            state.max_width = width;
147        }
148    });
149}
150
151/// Adds a measured duration to a profiling slot.
152pub fn record(slot: Slot, elapsed: std::time::Duration) {
153    if !enabled() {
154        return;
155    }
156    record_self(slot, elapsed.as_nanos());
157}
158
159fn record_self(slot: Slot, nanos: u128) {
160    STATE.with(|s| {
161        let mut state = s.borrow_mut();
162        let sample = &mut state.samples[slot.index()];
163        sample.count += 1;
164        sample.nanos += nanos;
165    });
166}
167
168fn report() {
169    let (mut entries, total, max_depth, max_width) = STATE.with(|s| {
170        let state = s.borrow();
171        let mut entries: Vec<(Slot, Sample)> = Vec::with_capacity(SLOT_COUNT);
172        for slot in [
173            Slot::Block,
174            Slot::Flex,
175            Slot::Grid,
176            Slot::Table,
177            Slot::Inline,
178            Slot::Intrinsic,
179            Slot::StyleClone,
180            Slot::Geometry,
181            Slot::Exclusions,
182        ] {
183            entries.push((slot, state.samples[slot.index()]));
184        }
185        (entries, state.total_nodes, state.max_depth, state.max_width)
186    });
187    if total < 500 {
188        return;
189    }
190    entries.sort_by_key(|a| std::cmp::Reverse(a.1.nanos));
191    let mut lines = String::new();
192    for (index, (slot, sample)) in entries.iter().enumerate().take(5) {
193        lines.push_str(&format!(
194            "\n[layout-prof] #{} {}: {:.3} ms ({} calls)",
195            index + 1,
196            slot.label(),
197            sample.nanos as f64 / 1_000_000.0,
198            sample.count
199        ));
200    }
201    let total_ms: f64 = entries.iter().map(|(_, s)| s.nanos as f64).sum::<f64>() / 1_000_000.0;
202    eprintln!(
203        "[layout-prof] root layout: entries={} max_depth={} max_children={} total={:.3} ms{}",
204        total, max_depth, max_width, total_ms, lines
205    );
206}
207
208/// Guard that owns the root layout report lifecycle and unwinds on every exit path.
209pub struct LayoutGuard {
210    is_root: bool,
211}
212
213impl LayoutGuard {
214    /// Enters a layout scope and returns a guard that reports on drop.
215    pub fn new() -> Self {
216        Self {
217            is_root: enter_layout(),
218        }
219    }
220}
221
222impl Default for LayoutGuard {
223    fn default() -> Self {
224        Self::new()
225    }
226}
227
228impl Drop for LayoutGuard {
229    fn drop(&mut self) {
230        leave_layout(self.is_root);
231    }
232}
233
234/// Guard that records elapsed time into a slot for its lexical scope.
235pub struct Scope {
236    enabled: bool,
237}
238
239impl Scope {
240    /// Starts timing a slot when profiling is enabled.
241    pub fn new(slot: Slot) -> Self {
242        let enabled = enabled();
243        if enabled {
244            FRAMES.with(|frames| {
245                frames.borrow_mut().push(Frame {
246                    slot,
247                    start: std::time::Instant::now(),
248                    child_nanos: 0,
249                });
250            });
251        }
252        Self { enabled }
253    }
254}
255
256impl Drop for Scope {
257    fn drop(&mut self) {
258        if !self.enabled {
259            return;
260        }
261        let popped = FRAMES.with(|frames| frames.borrow_mut().pop());
262        if let Some(frame) = popped {
263            let elapsed = frame.start.elapsed().as_nanos();
264            let exclusive = elapsed.saturating_sub(frame.child_nanos);
265            record_self(frame.slot, exclusive);
266            FRAMES.with(|frames| {
267                if let Some(parent) = frames.borrow_mut().last_mut() {
268                    parent.child_nanos += elapsed;
269                }
270            });
271        }
272    }
273}