Skip to main content

nativeview_engine/
profiler.rs

1use std::collections::VecDeque;
2use std::fmt::Write as _;
3
4use serde::{Deserialize, Serialize};
5
6use nativeview_abi::{DurationUs, FrameId};
7
8/// Exact microsecond breakdown across every pipeline stage so performance stays measurable.
9#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
10pub struct FrameTiming {
11    pub frame_id: FrameId,
12    pub op_count: u32,
13    pub mutation_count: u32,
14    pub reconcile_us: DurationUs,
15    pub encode_us: DurationUs,
16    pub decode_us: DurationUs,
17    pub layout_us: DurationUs,
18    pub diff_us: DurationUs,
19    pub mount_us: DurationUs,
20}
21
22impl FrameTiming {
23    pub fn total_us(&self) -> u64 {
24        self.reconcile_us.0
25            + self.encode_us.0
26            + self.decode_us.0
27            + self.layout_us.0
28            + self.diff_us.0
29            + self.mount_us.0
30    }
31}
32
33pub struct FrameProfiler {
34    capacity: usize,
35    frames: VecDeque<FrameTiming>,
36}
37
38impl FrameProfiler {
39    pub fn new(capacity: usize) -> Self {
40        Self {
41            capacity: capacity.max(1),
42            frames: VecDeque::with_capacity(capacity.max(1)),
43        }
44    }
45
46    pub fn record(&mut self, timing: FrameTiming) {
47        if self.frames.len() == self.capacity {
48            self.frames.pop_front();
49        }
50        self.frames.push_back(timing);
51    }
52
53    pub fn frames(&self) -> &VecDeque<FrameTiming> {
54        &self.frames
55    }
56
57    pub fn p50_total_us(&self) -> u64 {
58        self.percentile(0.50)
59    }
60
61    pub fn p99_total_us(&self) -> u64 {
62        self.percentile(0.99)
63    }
64
65    fn percentile(&self, p: f64) -> u64 {
66        if self.frames.is_empty() {
67            return 0;
68        }
69        let mut totals: Vec<u64> = self.frames.iter().map(FrameTiming::total_us).collect();
70        totals.sort_unstable();
71        let idx = ((totals.len() - 1) as f64 * p).round() as usize;
72        totals[idx.min(totals.len() - 1)]
73    }
74
75    /// Exports recorded frames in Chrome Trace Event Format (loadable directly in Perfetto UI).
76    pub fn to_chrome_trace_json(&self) -> String {
77        if self.frames.is_empty() {
78            return "[]".to_owned();
79        }
80        let mut out = String::with_capacity(self.frames.len() * 6 * 120 + 4);
81        out.push_str("[\n");
82        let mut cursor_ts = 0u64;
83        let mut first = true;
84        for f in &self.frames {
85            let stages = [
86                ("rust.reconcile", f.reconcile_us.0, 1u32),
87                ("abi.encode", f.encode_us.0, 1u32),
88                ("backend.decode", f.decode_us.0, 2u32),
89                ("backend.layout", f.layout_us.0, 2u32),
90                ("backend.diff", f.diff_us.0, 2u32),
91                ("backend.mount", f.mount_us.0, 3u32),
92            ];
93            for (name, dur, tid) in stages {
94                if !first {
95                    out.push_str(",\n");
96                }
97                first = false;
98                out.push_str("  {\n    \"name\": \"");
99                write_json_escaped(&mut out, name);
100                let _ = write!(
101                    out,
102                    "\",\n    \"cat\": \"nv.frame\",\n    \"ph\": \"X\",\n    \"ts\": {cursor_ts},\n    \"dur\": {dur},\n    \"pid\": 1,\n    \"tid\": {tid}\n  }}"
103                );
104                cursor_ts += dur.max(1);
105            }
106            cursor_ts += 100;
107        }
108        out.push_str("\n]");
109        out
110    }
111}
112
113fn write_json_escaped(out: &mut String, s: &str) {
114    for ch in s.chars() {
115        match ch {
116            '"' => out.push_str("\\\""),
117            '\\' => out.push_str("\\\\"),
118            '\n' => out.push_str("\\n"),
119            '\r' => out.push_str("\\r"),
120            '\t' => out.push_str("\\t"),
121            c if (c as u32) < 0x20 => {
122                let _ = write!(out, "\\u{:04x}", c as u32);
123            }
124            c => out.push(c),
125        }
126    }
127}