1use std::cell::RefCell;
6use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
7use std::time::Instant;
8
9static ENABLED: AtomicU8 = AtomicU8::new(0);
11
12static TRACING: AtomicBool = AtomicBool::new(false);
13
14pub fn set_tracing(on: bool) {
15 TRACING.store(on, Ordering::Relaxed);
16}
17
18pub fn env_enabled() -> bool {
19 env_on()
20}
21
22#[inline]
23pub fn enabled() -> bool {
24 TRACING.load(Ordering::Relaxed) || env_on()
25}
26
27#[inline]
28fn env_on() -> bool {
29 match ENABLED.load(Ordering::Relaxed) {
30 1 => false,
31 2 => true,
32 _ => {
33 let on = std::env::var("SK_PERF")
34 .map(|v| {
35 let v = v.trim().to_ascii_lowercase();
36 !(v.is_empty() || v == "0" || v == "false" || v == "off")
37 })
38 .unwrap_or(false);
39 ENABLED.store(if on { 2 } else { 1 }, Ordering::Relaxed);
40 on
41 }
42 }
43}
44
45#[derive(Clone, Copy, Debug)]
46pub struct Phases {
47 pub restyle_passes: u32,
49 pub restyle_ms: f32,
50 pub restyle_max_ms: f32,
51 pub inline_ms: f32,
52 pub cascade_ms: f32,
53 pub match_ms: f32,
54 pub vars_ms: f32,
55 pub fold_ms: f32,
56 pub store_ms: f32,
57 pub nodes_cascaded: u64,
58 pub rules_tested: u64,
59 pub rules_split: sk_css::perf::Split,
61 pub share_asked: u64,
62 pub share_hits: u64,
63
64 pub build_passes: u32,
65 pub cached_renders: u32,
67 pub cache_offers: u32,
68 pub cache_standdowns: u32,
69 pub build_ms: f32,
70 pub build_max_ms: f32,
71 pub elements_built: u64,
72
73 pub layout_req_ms: f32,
74 pub taffy_ms: f32,
75 pub prepaint_ms: f32,
76 pub paint_ms: f32,
77 pub draw_passes: u32,
78
79 pub js_passes: u32,
81 pub js_ms: f32,
82 pub js_max_ms: f32,
83
84 pub restyle_full: u32,
85 pub nodes_changed: u64,
86 pub full_reasons: [u32; FullReason::COUNT],
87 pub recompiles: u32,
88 pub recompile_ms: f32,
89 pub sync_layouts: u32,
90 pub sync_layout_ms: f32,
91 pub sync_layout_max_ms: f32,
92 pub sync_layout_refused: u32,
93 pub sync_by: [u32; SyncCaller::COUNT],
94 pub sync_tail: u32,
96 pub sync_tail_free: u32,
97 pub observer_steps: u32,
101 pub observer_rounds: u32,
102 pub observer_relayouts: u32,
103 pub observer_relayout_ms: f32,
104 pub observer_ms: f32,
105 pub observer_loop_errors: u32,
106 pub dom_ops: [u32; DomOp::COUNT],
107 pub dom_first: Option<Instant>,
109 pub dom_last: Option<Instant>,
110 pub layout_reads: u32,
111 pub scroll_reads: u32,
112 pub style_reads: u32,
113 pub queries: u32,
114 pub style_flushes: u32,
115 pub resample_sync: u32,
116 pub resample_sync_ms: f32,
117 pub resample_async: u32,
118 pub fonts_registered: u32,
119 pub font_bytes: u64,
120 pub img_srcs: u32,
121}
122
123#[derive(Clone, Copy, Debug)]
124pub enum FullReason {
125 Stylesheet = 0,
126 Env = 1,
127 StyleElement = 2,
128 Fonts = 3,
129 ViewportBasis = 4,
130 RemBasis = 5,
131}
132
133impl FullReason {
134 pub const COUNT: usize = 6;
135 pub const NAMES: [&'static str; Self::COUNT] = [
136 "stylesheet",
137 "env",
138 "style-element",
139 "fonts",
140 "viewport-basis",
141 "rem-basis",
142 ];
143}
144
145#[derive(Clone, Copy, Debug)]
146pub enum SyncCaller {
147 Bounds = 0,
149 Scroll = 1,
151 Focus = 2,
153}
154
155impl SyncCaller {
156 pub const COUNT: usize = 3;
157 pub const NAMES: [&'static str; Self::COUNT] = ["bounds", "scroll", "focus"];
158}
159
160#[derive(Clone, Copy, Debug)]
162pub enum DomOp {
163 Create = 0,
165 Insert = 1,
167 Remove = 2,
169 Class = 3,
171 Style = 4,
173 Prop = 5,
175 Text = 6,
177 Other = 7,
179}
180
181impl DomOp {
182 pub const COUNT: usize = 8;
183 pub const NAMES: [&'static str; Self::COUNT] = [
184 "create", "insert", "remove", "class", "style", "prop", "text", "other",
185 ];
186}
187
188const ZERO: Phases = Phases {
189 restyle_passes: 0,
190 restyle_ms: 0.0,
191 restyle_max_ms: 0.0,
192 inline_ms: 0.0,
193 cascade_ms: 0.0,
194 match_ms: 0.0,
195 vars_ms: 0.0,
196 fold_ms: 0.0,
197 store_ms: 0.0,
198 nodes_cascaded: 0,
199 rules_tested: 0,
200 rules_split: sk_css::perf::Split {
201 by_bucket: [0; 6],
202 matched: 0,
203 },
204 share_asked: 0,
205 share_hits: 0,
206 build_passes: 0,
207 cached_renders: 0,
208 cache_offers: 0,
209 cache_standdowns: 0,
210 build_ms: 0.0,
211 build_max_ms: 0.0,
212 elements_built: 0,
213 layout_req_ms: 0.0,
214 taffy_ms: 0.0,
215 prepaint_ms: 0.0,
216 paint_ms: 0.0,
217 draw_passes: 0,
218 js_passes: 0,
219 js_ms: 0.0,
220 js_max_ms: 0.0,
221 restyle_full: 0,
222 nodes_changed: 0,
223 full_reasons: [0; FullReason::COUNT],
224 recompiles: 0,
225 recompile_ms: 0.0,
226 sync_layouts: 0,
227 sync_layout_ms: 0.0,
228 sync_layout_max_ms: 0.0,
229 sync_layout_refused: 0,
230 sync_by: [0; SyncCaller::COUNT],
231 sync_tail: 0,
232 sync_tail_free: 0,
233 observer_steps: 0,
234 observer_rounds: 0,
235 observer_relayouts: 0,
236 observer_relayout_ms: 0.0,
237 observer_ms: 0.0,
238 observer_loop_errors: 0,
239 dom_ops: [0; DomOp::COUNT],
240 dom_first: None,
241 dom_last: None,
242 layout_reads: 0,
243 scroll_reads: 0,
244 style_reads: 0,
245 queries: 0,
246 style_flushes: 0,
247 resample_sync: 0,
248 resample_sync_ms: 0.0,
249 resample_async: 0,
250 fonts_registered: 0,
251 font_bytes: 0,
252 img_srcs: 0,
253};
254
255impl Default for Phases {
256 fn default() -> Self {
257 ZERO
258 }
259}
260
261thread_local! {
262 static PHASES: RefCell<Phases> = const { RefCell::new(ZERO) };
263 static LAYOUT_DONE: RefCell<Option<Instant>> = const { RefCell::new(None) };
264}
265
266fn with(f: impl FnOnce(&mut Phases)) {
267 PHASES.with(|p| f(&mut p.borrow_mut()));
268}
269
270pub fn take() -> Option<Phases> {
271 if !enabled() {
272 return None;
273 }
274 let taken = PHASES.with(|p| std::mem::take(&mut *p.borrow_mut()));
275 (taken.restyle_passes > 0 || taken.build_passes > 0 || taken.js_passes > 0).then_some(taken)
276}
277
278pub fn take_all() -> Phases {
280 PHASES.with(|p| std::mem::take(&mut *p.borrow_mut()))
281}
282
283pub struct Span(Option<Instant>);
286
287impl Span {
288 #[inline]
289 pub fn start() -> Span {
290 Span(enabled().then(Instant::now))
291 }
292
293 #[inline]
294 pub fn ms(&self) -> f32 {
295 match self.0 {
296 Some(t) => t.elapsed().as_secs_f32() * 1000.0,
297 None => 0.0,
298 }
299 }
300}
301
302pub fn note_restyle(total_ms: f32, inline_ms: f32, cascade_ms: f32, store_ms: f32, nodes: u64) {
303 if !enabled() {
304 return;
305 }
306 sk_runtime::redjs::profiling::counter("nodesCascaded", nodes);
307 let (rules, match_ms, vars_ms, fold_ms) = sk_css::perf::take();
308 sk_runtime::redjs::profiling::counter("selectorsTested", rules);
309 let split = sk_css::perf::take_split();
310 let (share_asked, share_hits) = sk_css::perf::take_share();
311 with(|p| {
312 p.restyle_passes += 1;
313 p.restyle_ms += total_ms;
314 p.restyle_max_ms = p.restyle_max_ms.max(total_ms);
315 p.inline_ms += inline_ms;
316 p.cascade_ms += cascade_ms;
317 p.match_ms += match_ms;
318 p.vars_ms += vars_ms;
319 p.fold_ms += fold_ms;
320 p.store_ms += store_ms;
321 p.nodes_cascaded += nodes;
322 p.rules_tested += rules;
323 for (total, n) in p.rules_split.by_bucket.iter_mut().zip(split.by_bucket) {
324 *total += n;
325 }
326 p.rules_split.matched += split.matched;
327 p.share_asked += share_asked;
328 p.share_hits += share_hits;
329 });
330}
331
332pub fn note_build(total_ms: f32, elements: u64) {
333 if !enabled() {
334 return;
335 }
336 sk_runtime::redjs::profiling::counter("elementsBuilt", elements);
337 with(|p| {
338 p.build_passes += 1;
339 p.build_ms += total_ms;
340 p.build_max_ms = p.build_max_ms.max(total_ms);
341 p.elements_built += elements;
342 });
343}
344
345#[inline]
346pub fn note_cache_offer(stood_down: bool) {
347 if !enabled() {
348 return;
349 }
350 with(|p| {
351 if stood_down {
352 p.cache_standdowns += 1;
353 } else {
354 p.cache_offers += 1;
355 }
356 });
357}
358
359pub fn note_build_extra(total_ms: f32, elements: u64) {
360 if !enabled() {
361 return;
362 }
363 with(|p| {
364 p.build_ms += total_ms;
365 p.elements_built += elements;
366 p.cached_renders += 1;
367 p.prepaint_ms -= total_ms;
370 });
371}
372
373pub fn note_layout_req(ms: f32) {
374 if !enabled() {
375 return;
376 }
377 LAYOUT_DONE.with(|c| *c.borrow_mut() = Some(Instant::now()));
378 with(|p| {
379 p.layout_req_ms += ms;
380 p.draw_passes += 1;
381 });
382}
383
384pub fn note_taffy_gap() {
385 if !enabled() {
386 return;
387 }
388 let Some(t) = LAYOUT_DONE.with(|c| c.borrow_mut().take()) else {
389 return;
390 };
391 let ended = Instant::now();
392 let ms = ended.duration_since(t).as_secs_f32() * 1000.0;
393 sk_runtime::redjs::profiling::interval("layout", "Taffy layout", t, ended);
394 with(|p| p.taffy_ms += ms);
395}
396
397pub fn note_prepaint(ms: f32) {
398 if !enabled() {
399 return;
400 }
401 with(|p| p.prepaint_ms += ms);
402}
403
404pub fn note_paint(ms: f32) {
405 if !enabled() {
406 return;
407 }
408 with(|p| p.paint_ms += ms);
409}
410
411pub fn note_restyle_shape(full: bool, changed: u64) {
412 if !enabled() {
413 return;
414 }
415 with(|p| {
416 p.restyle_full += u32::from(full);
417 p.nodes_changed += changed;
418 });
419}
420
421#[inline]
422pub fn note_full(reason: FullReason) {
423 if !enabled() {
424 return;
425 }
426 with(|p| p.full_reasons[reason as usize] += 1);
427}
428
429static LIVE_BYTES_PROBE: std::sync::OnceLock<fn() -> Option<i64>> = std::sync::OnceLock::new();
433static SHEET_COMPILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
434static SHEET_COMPILE_US: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
435static SHEET_SOURCE_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
436static SHEET_GROWTH: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);
437static SHEET_GROWTH_SEEN: AtomicBool = AtomicBool::new(false);
438
439pub fn set_live_bytes_probe(f: fn() -> Option<i64>) {
440 let _ = LIVE_BYTES_PROBE.set(f);
441}
442
443pub fn live_bytes() -> Option<i64> {
444 LIVE_BYTES_PROBE.get().and_then(|f| f())
445}
446
447pub fn note_sheet_compile(ms: f32, source_len: usize, before: Option<i64>, after: Option<i64>) {
449 use std::sync::atomic::Ordering::Relaxed;
450 SHEET_COMPILES.fetch_add(1, Relaxed);
451 SHEET_COMPILE_US.fetch_add((ms * 1000.0) as u64, Relaxed);
452 SHEET_SOURCE_BYTES.fetch_add(source_len as u64, Relaxed);
453 if let (Some(b), Some(a)) = (before, after) {
454 SHEET_GROWTH.fetch_add(a - b, Relaxed);
455 SHEET_GROWTH_SEEN.store(true, Relaxed);
456 }
457}
458
459pub fn sheet_compiles() -> (u64, f64, u64, Option<i64>) {
462 use std::sync::atomic::Ordering::Relaxed;
463 (
464 SHEET_COMPILES.load(Relaxed),
465 SHEET_COMPILE_US.load(Relaxed) as f64 / 1000.0,
466 SHEET_SOURCE_BYTES.load(Relaxed),
467 SHEET_GROWTH_SEEN
468 .load(Relaxed)
469 .then(|| SHEET_GROWTH.load(Relaxed)),
470 )
471}
472
473pub fn note_recompile(ms: f32) {
474 if !enabled() {
475 return;
476 }
477 with(|p| {
478 p.recompiles += 1;
479 p.recompile_ms += ms;
480 });
481}
482
483pub fn note_sync_tail(free: bool) {
486 if !enabled() {
487 return;
488 }
489 with(|p| {
490 p.sync_tail += 1;
491 if free {
492 p.sync_tail_free += 1;
493 }
494 });
495}
496
497pub fn note_observers(rounds: u32, relayouts: u32, relayout_ms: f32, ms: f32, loop_error: bool) {
498 if !enabled() {
499 return;
500 }
501 with(|p| {
502 p.observer_steps += 1;
503 p.observer_rounds += rounds;
504 p.observer_relayouts += relayouts;
505 p.observer_relayout_ms += relayout_ms;
506 p.observer_ms += ms.max(0.0);
507 p.observer_loop_errors += u32::from(loop_error);
508 });
509}
510
511pub fn note_sync_layout(caller: SyncCaller, drew: bool, ms: f32) {
512 if !enabled() {
513 return;
514 }
515 if drew {
516 sk_runtime::redjs::profiling::counter("forcedLayouts", 1);
517 }
518 with(|p| {
519 p.sync_by[caller as usize] += 1;
520 if drew {
521 p.sync_layouts += 1;
522 p.sync_layout_ms += ms;
523 p.sync_layout_max_ms = p.sync_layout_max_ms.max(ms);
524 } else {
525 p.sync_layout_refused += 1;
526 }
527 });
528}
529
530#[inline]
531pub fn note_dom(op: DomOp) {
532 if !enabled() {
533 return;
534 }
535 if sk_runtime::redjs::profiling::enabled() {
536 sk_runtime::redjs::profiling::counter("domWrites", 1);
537 sk_runtime::redjs::profiling::counter(&format!("dom.{}", DomOp::NAMES[op as usize]), 1);
538 }
539 let now = Instant::now();
540 with(|p| {
541 p.dom_ops[op as usize] += 1;
542 if p.dom_first.is_none() {
543 p.dom_first = Some(now);
544 }
545 p.dom_last = Some(now);
546 });
547}
548
549#[derive(Clone, Copy)]
550pub enum Read {
551 Layout,
552 Scroll,
553 Style,
554 Query,
555}
556
557#[inline]
558pub fn note_read(kind: Read) {
559 if !enabled() {
560 return;
561 }
562 sk_runtime::redjs::profiling::counter(
563 match kind {
564 Read::Layout => "layoutReads",
565 Read::Scroll => "scrollReads",
566 Read::Style => "styleReads",
567 Read::Query => "selectorQueries",
568 },
569 1,
570 );
571 with(|p| match kind {
572 Read::Layout => p.layout_reads += 1,
573 Read::Scroll => p.scroll_reads += 1,
574 Read::Style => p.style_reads += 1,
575 Read::Query => p.queries += 1,
576 });
577}
578
579pub fn note_style_flush() {
580 if !enabled() {
581 return;
582 }
583 with(|p| p.style_flushes += 1);
584}
585
586pub fn note_resample(sync_ms: Option<f32>) {
587 if !enabled() {
588 return;
589 }
590 with(|p| match sync_ms {
591 Some(ms) => {
592 p.resample_sync += 1;
593 p.resample_sync_ms += ms;
594 }
595 None => p.resample_async += 1,
596 });
597}
598
599pub fn note_fonts(count: u32, bytes: u64) {
600 if !enabled() {
601 return;
602 }
603 with(|p| {
604 p.fonts_registered += count;
605 p.font_bytes += bytes;
606 });
607}
608
609pub fn note_img_src() {
610 if !enabled() {
611 return;
612 }
613 with(|p| p.img_srcs += 1);
614}
615
616pub fn note_js(total_ms: f32) {
617 if !enabled() {
618 return;
619 }
620 with(|p| {
621 p.js_passes += 1;
622 p.js_ms += total_ms;
623 p.js_max_ms = p.js_max_ms.max(total_ms);
624 });
625}