mgui-runtime 0.2.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
Documentation
//! 阶段 B3:Frame Profile — CPU paint 耗时采样
//!
//! **目标**:每帧记录 CPU 端 paint(layout + collect paint list + GPU submit)耗时,
//! 每秒聚合输出 avg/min/max/p50/p99/fps 到 env_logger,辅助性能调优。
//!
//! **设计**:
//! - 1024-slot ring buffer(每帧覆盖,内存 ~4KB)
//! - `record(paint_us)` 写入;`maybe_report()` 每秒触发,返回 `FrameReport`
//! - 简洁版:不依赖 `wgpu-profiler`/`puffin`,纯 std::time + log
//!
//! **不依赖** GPU 端 timer(那要 timestamp query / wgpu-profiler,复杂)。
//! 这里只测 CPU 侧:从 `render_frame()` 开始到 `queue.submit()` 结束。
//!
//! ## 后续扩展(MVP 后)
//! - 拆 CPU 端:`layout_us` / `collect_paint_us` / `submit_us` 三段
//! - GPU 端:wgpu timestamp query(wgpu 30 支持,但要 enable feature)
//! - GUI overlay:左上角显示 fps(用 TextWidget)

use std::time::{Duration, Instant};

/// 阶段 B3:FrameProfile — 每秒聚合 CPU paint 耗时
///
/// **窗口模型**(不是 ring buffer):每次 maybe_report 把当前 samples 全清,
/// `frames` 就是这 1 秒内的真实帧数。这样 fps 永远 = `samples.len()`,不会随时间涨。
/// 之前用 ring buffer 是错的:程序跑 ~17s 后 samples 满到 1024,fps 永远显示 1024。
pub struct FrameProfile {
    /// 当前窗口的 CPU paint 耗时样本(微秒) — 每次 report 后清空
    samples: Vec<u32>,
    /// 单窗口最大样本数(防止异常情况下无限增长,默认 1024)
    capacity: usize,
    /// 下次 report 时刻
    next_report_at: Instant,
    /// 自启动累计帧数
    frame_count: u32,
    /// report 间隔(默认 1 秒)
    report_interval: Duration,
}

impl Default for FrameProfile {
    fn default() -> Self {
        Self::new()
    }
}

impl FrameProfile {
    pub fn new() -> Self {
        Self::with_capacity(1024, Duration::from_secs(1))
    }

    pub fn with_capacity(capacity: usize, report_interval: Duration) -> Self {
        Self {
            samples: Vec::with_capacity(capacity),
            capacity,
            next_report_at: Instant::now() + report_interval,
            frame_count: 0,
            report_interval,
        }
    }

    /// 阶段 B3:记录一帧 CPU paint 耗时
    pub fn record(&mut self, paint_us: u32) {
        if self.samples.len() < self.capacity {
            self.samples.push(paint_us);
        }
        // 满了就丢弃(异常 case:1 秒内 >1024 帧 = 1024fps+,实际不会发生)
        // 不能用 ring buffer 覆盖老样本 — 那样 fps 会一直 = capacity
        self.frame_count += 1;
    }

    /// 阶段 B3:每秒触发一次,返回这 1 秒的聚合报告;**报告后清空窗口**
    ///
    /// **调用时机**:每帧 paint 末尾调一次;返回 Some = 到了 report 时刻。
    pub fn maybe_report(&mut self) -> Option<FrameReport> {
        let now = Instant::now();
        if now < self.next_report_at {
            return None;
        }
        // 推进下次 report 时刻(避免 drift)
        self.next_report_at = now + self.report_interval;
        if self.samples.is_empty() {
            return None;
        }

        // 阶段 B3 修复:用 std::mem::take 取出 samples,清空窗口
        // 之前用 self.samples.clone() 留着 — 第二次 report 就累计到 2 秒的样本
        let mut sorted: Vec<u32> = std::mem::take(&mut self.samples);
        sorted.sort_unstable();

        let n = sorted.len() as u32;
        let total: u64 = sorted.iter().map(|&x| x as u64).sum();
        let avg_us = (total / n as u64) as u32;
        let min_us = *sorted.first().unwrap();
        let max_us = *sorted.last().unwrap();
        let p50_us = sorted[(n as usize * 50) / 100];
        let p95_us = sorted[(n as usize * 95) / 100];
        let p99_us = sorted[(n as usize * 99) / 100];

        // 阶段 B3 修复:fps = n(本窗口 1 秒内的帧数),不是 sample 累计
        let fps = n as f32;

        Some(FrameReport { frames: n, avg_us, min_us, max_us, p50_us, p95_us, p99_us, fps })
    }
}

/// 阶段 B3:聚合报告(每秒输出一次)
#[derive(Debug, Clone, Copy)]
pub struct FrameReport {
    /// 这秒内累计帧数
    pub frames: u32,
    /// CPU paint 平均耗时(微秒)
    pub avg_us: u32,
    pub min_us: u32,
    pub max_us: u32,
    pub p50_us: u32,
    pub p95_us: u32,
    pub p99_us: u32,
    /// 估算 fps(报告间隔 1s 时 = frames)
    pub fps: f32,
}

impl FrameReport {
    pub fn log(&self) {
        log::info!(
            "[B3 frame profile] fps={:.0} avg={}us min={}us p50={}us p95={}us p99={}us max={}us (frames={})",
            self.fps,
            self.avg_us,
            self.min_us,
            self.p50_us,
            self.p95_us,
            self.p99_us,
            self.max_us,
            self.frames
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn profile_record_and_report() {
        let mut p = FrameProfile::with_capacity(8, Duration::from_millis(50));
        // 模拟 5 帧,每帧 100us
        for _ in 0..5 {
            p.record(100);
        }
        // 还没到 50ms,应 None
        assert!(p.maybe_report().is_none());
        // 等过 50ms
        std::thread::sleep(Duration::from_millis(60));
        let r = p.maybe_report().expect("should report");
        assert_eq!(r.frames, 5);
        assert_eq!(r.min_us, 100);
        assert_eq!(r.max_us, 100);
        assert_eq!(r.avg_us, 100);
        assert_eq!(r.p50_us, 100);
    }

    #[test]
    fn profile_window_clears_each_report() {
        // 阶段 B3 修复:不再用 ring buffer,窗口清空模型
        // - 第 1 个 1s 窗口:写 5 帧,report → frames=5
        // - 第 2 个 1s 窗口:写 3 帧,report → frames=3(不是 8 累计)
        let mut p = FrameProfile::with_capacity(8, Duration::from_millis(50));
        for _ in 0..5 {
            p.record(100);
        }
        std::thread::sleep(Duration::from_millis(60));
        let r1 = p.maybe_report().expect("should report");
        assert_eq!(r1.frames, 5, "第 1 窗口 5 帧");

        // 第 2 窗口:再写 3 帧不同值
        for _ in 0..3 {
            p.record(200);
        }
        std::thread::sleep(Duration::from_millis(60));
        let r2 = p.maybe_report().expect("should report");
        assert_eq!(r2.frames, 3, "第 2 窗口 3 帧(不是 5+3 累计)");
        assert_eq!(r2.avg_us, 200);
        assert_eq!(r2.min_us, 200);
        assert_eq!(r2.max_us, 200);
    }

    #[test]
    fn profile_percentile_correct() {
        let mut p = FrameProfile::with_capacity(100, Duration::from_millis(50));
        // 写 1..=100
        for i in 1..=100 {
            p.record(i);
        }
        std::thread::sleep(Duration::from_millis(60));
        let r = p.maybe_report().expect("should report");
        assert_eq!(r.frames, 100);
        assert_eq!(r.min_us, 1);
        assert_eq!(r.max_us, 100);
        assert!((r.avg_us as i64 - 50).unsigned_abs() < 2, "avg≈50, got {}", r.avg_us);
        // p50 = sorted[50] = 51 (1-indexed)
        assert_eq!(r.p50_us, 51);
        // p99 = sorted[99] = 100
        assert_eq!(r.p99_us, 100);
    }
}