Skip to main content

mgui_runtime/
profile.rs

1//! 阶段 B3:Frame Profile — CPU paint 耗时采样
2//!
3//! **目标**:每帧记录 CPU 端 paint(layout + collect paint list + GPU submit)耗时,
4//! 每秒聚合输出 avg/min/max/p50/p99/fps 到 env_logger,辅助性能调优。
5//!
6//! **设计**:
7//! - 1024-slot ring buffer(每帧覆盖,内存 ~4KB)
8//! - `record(paint_us)` 写入;`maybe_report()` 每秒触发,返回 `FrameReport`
9//! - 简洁版:不依赖 `wgpu-profiler`/`puffin`,纯 std::time + log
10//!
11//! **不依赖** GPU 端 timer(那要 timestamp query / wgpu-profiler,复杂)。
12//! 这里只测 CPU 侧:从 `render_frame()` 开始到 `queue.submit()` 结束。
13//!
14//! ## 后续扩展(MVP 后)
15//! - 拆 CPU 端:`layout_us` / `collect_paint_us` / `submit_us` 三段
16//! - GPU 端:wgpu timestamp query(wgpu 30 支持,但要 enable feature)
17//! - GUI overlay:左上角显示 fps(用 TextWidget)
18
19use std::time::{Duration, Instant};
20
21/// 阶段 B3:FrameProfile — 每秒聚合 CPU paint 耗时
22///
23/// **窗口模型**(不是 ring buffer):每次 maybe_report 把当前 samples 全清,
24/// `frames` 就是这 1 秒内的真实帧数。这样 fps 永远 = `samples.len()`,不会随时间涨。
25/// 之前用 ring buffer 是错的:程序跑 ~17s 后 samples 满到 1024,fps 永远显示 1024。
26pub struct FrameProfile {
27    /// 当前窗口的 CPU paint 耗时样本(微秒) — 每次 report 后清空
28    samples: Vec<u32>,
29    /// 单窗口最大样本数(防止异常情况下无限增长,默认 1024)
30    capacity: usize,
31    /// 下次 report 时刻
32    next_report_at: Instant,
33    /// 自启动累计帧数
34    frame_count: u32,
35    /// report 间隔(默认 1 秒)
36    report_interval: Duration,
37}
38
39impl Default for FrameProfile {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl FrameProfile {
46    pub fn new() -> Self {
47        Self::with_capacity(1024, Duration::from_secs(1))
48    }
49
50    pub fn with_capacity(capacity: usize, report_interval: Duration) -> Self {
51        Self {
52            samples: Vec::with_capacity(capacity),
53            capacity,
54            next_report_at: Instant::now() + report_interval,
55            frame_count: 0,
56            report_interval,
57        }
58    }
59
60    /// 阶段 B3:记录一帧 CPU paint 耗时
61    pub fn record(&mut self, paint_us: u32) {
62        if self.samples.len() < self.capacity {
63            self.samples.push(paint_us);
64        }
65        // 满了就丢弃(异常 case:1 秒内 >1024 帧 = 1024fps+,实际不会发生)
66        // 不能用 ring buffer 覆盖老样本 — 那样 fps 会一直 = capacity
67        self.frame_count += 1;
68    }
69
70    /// 阶段 B3:每秒触发一次,返回这 1 秒的聚合报告;**报告后清空窗口**
71    ///
72    /// **调用时机**:每帧 paint 末尾调一次;返回 Some = 到了 report 时刻。
73    pub fn maybe_report(&mut self) -> Option<FrameReport> {
74        let now = Instant::now();
75        if now < self.next_report_at {
76            return None;
77        }
78        // 推进下次 report 时刻(避免 drift)
79        self.next_report_at = now + self.report_interval;
80        if self.samples.is_empty() {
81            return None;
82        }
83
84        // 阶段 B3 修复:用 std::mem::take 取出 samples,清空窗口
85        // 之前用 self.samples.clone() 留着 — 第二次 report 就累计到 2 秒的样本
86        let mut sorted: Vec<u32> = std::mem::take(&mut self.samples);
87        sorted.sort_unstable();
88
89        let n = sorted.len() as u32;
90        let total: u64 = sorted.iter().map(|&x| x as u64).sum();
91        let avg_us = (total / n as u64) as u32;
92        let min_us = *sorted.first().unwrap();
93        let max_us = *sorted.last().unwrap();
94        let p50_us = sorted[(n as usize * 50) / 100];
95        let p95_us = sorted[(n as usize * 95) / 100];
96        let p99_us = sorted[(n as usize * 99) / 100];
97
98        // 阶段 B3 修复:fps = n(本窗口 1 秒内的帧数),不是 sample 累计
99        let fps = n as f32;
100
101        Some(FrameReport { frames: n, avg_us, min_us, max_us, p50_us, p95_us, p99_us, fps })
102    }
103}
104
105/// 阶段 B3:聚合报告(每秒输出一次)
106#[derive(Debug, Clone, Copy)]
107pub struct FrameReport {
108    /// 这秒内累计帧数
109    pub frames: u32,
110    /// CPU paint 平均耗时(微秒)
111    pub avg_us: u32,
112    pub min_us: u32,
113    pub max_us: u32,
114    pub p50_us: u32,
115    pub p95_us: u32,
116    pub p99_us: u32,
117    /// 估算 fps(报告间隔 1s 时 = frames)
118    pub fps: f32,
119}
120
121impl FrameReport {
122    pub fn log(&self) {
123        log::info!(
124            "[B3 frame profile] fps={:.0} avg={}us min={}us p50={}us p95={}us p99={}us max={}us (frames={})",
125            self.fps,
126            self.avg_us,
127            self.min_us,
128            self.p50_us,
129            self.p95_us,
130            self.p99_us,
131            self.max_us,
132            self.frames
133        );
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn profile_record_and_report() {
143        let mut p = FrameProfile::with_capacity(8, Duration::from_millis(50));
144        // 模拟 5 帧,每帧 100us
145        for _ in 0..5 {
146            p.record(100);
147        }
148        // 还没到 50ms,应 None
149        assert!(p.maybe_report().is_none());
150        // 等过 50ms
151        std::thread::sleep(Duration::from_millis(60));
152        let r = p.maybe_report().expect("should report");
153        assert_eq!(r.frames, 5);
154        assert_eq!(r.min_us, 100);
155        assert_eq!(r.max_us, 100);
156        assert_eq!(r.avg_us, 100);
157        assert_eq!(r.p50_us, 100);
158    }
159
160    #[test]
161    fn profile_window_clears_each_report() {
162        // 阶段 B3 修复:不再用 ring buffer,窗口清空模型
163        // - 第 1 个 1s 窗口:写 5 帧,report → frames=5
164        // - 第 2 个 1s 窗口:写 3 帧,report → frames=3(不是 8 累计)
165        let mut p = FrameProfile::with_capacity(8, Duration::from_millis(50));
166        for _ in 0..5 {
167            p.record(100);
168        }
169        std::thread::sleep(Duration::from_millis(60));
170        let r1 = p.maybe_report().expect("should report");
171        assert_eq!(r1.frames, 5, "第 1 窗口 5 帧");
172
173        // 第 2 窗口:再写 3 帧不同值
174        for _ in 0..3 {
175            p.record(200);
176        }
177        std::thread::sleep(Duration::from_millis(60));
178        let r2 = p.maybe_report().expect("should report");
179        assert_eq!(r2.frames, 3, "第 2 窗口 3 帧(不是 5+3 累计)");
180        assert_eq!(r2.avg_us, 200);
181        assert_eq!(r2.min_us, 200);
182        assert_eq!(r2.max_us, 200);
183    }
184
185    #[test]
186    fn profile_percentile_correct() {
187        let mut p = FrameProfile::with_capacity(100, Duration::from_millis(50));
188        // 写 1..=100
189        for i in 1..=100 {
190            p.record(i);
191        }
192        std::thread::sleep(Duration::from_millis(60));
193        let r = p.maybe_report().expect("should report");
194        assert_eq!(r.frames, 100);
195        assert_eq!(r.min_us, 1);
196        assert_eq!(r.max_us, 100);
197        assert!((r.avg_us as i64 - 50).unsigned_abs() < 2, "avg≈50, got {}", r.avg_us);
198        // p50 = sorted[50] = 51 (1-indexed)
199        assert_eq!(r.p50_us, 51);
200        // p99 = sorted[99] = 100
201        assert_eq!(r.p99_us, 100);
202    }
203}