315. 主循环 FPS 计数器

为 main.py 添加一个简单的周期性 FPS 计数器。

315 / 356 · tests/chapter_10_performance/test_315_main_fps_counter.py

需要更新的文件

main.py

为什么需要这一步

在优化 pygame 渲染或模拟器速度之前,手动运行器应当在终端中显示一个简单的端到端 FPS 信号。

该 FPS 计数器应测量完整的手动帧路径

Console.step_until_next_frame()
Console.render_framebuffer()
draw_framebuffer(...)
pygame.display.flip()

建议的实现示例

import time

FPS_REPORT_INTERVAL_SECONDS = 1.0

...

running = True
last_fps_report_time = time.perf_counter()
frames_since_last_report = 0

while running:
    ...

    executed = console.step_until_next_frame()
    framebuffer = console.render_framebuffer()
    draw_framebuffer(window, framebuffer, SCALE)
    pygame.display.flip()

    frames_since_last_report += 1
    now = time.perf_counter()
    elapsed = now - last_fps_report_time

    if elapsed >= FPS_REPORT_INTERVAL_SECONDS:
        fps = frames_since_last_report / elapsed
        print(f"fps={fps:.1f}")
        frames_since_last_report = 0
        last_fps_report_time = now

重要提示

这里刻意保持简单。它不会将模拟时间与渲染时间区分开来,只是在开始优化工作之前,在终端上提供一个可见的信号。

为什么要做源码结构测试?main.py 会打开 pygame 并运行一个手动循环。自动化测试不得调用 main()、打开窗口,也不得要求使用商业 ROM。

本步骤范围之外

  • 优化 pygame 绘制
  • 帧节奏 / 速度上限
  • 对各个子系统分别进行性能分析
  • 启动 PyPy
  • 从 pytest 中调用 main()

运行本课

uv run pytest tests/chapter_10_performance/test_315_main_fps_counter.py -v