// ge_fps.c #include "ge_fps.h" // 初始化FPS控制器 void ge_fps_init(ge_fps_controller_t* fps_ctrl, ge_u32_t target_fps, ge_fps_get_ms_func_t get_ms, ge_fps_sleep_ms_func_t sleep_ms) { fps_ctrl->target_fps = target_fps; fps_ctrl->frame_duration = 1000 / target_fps; fps_ctrl->last_frame_time = get_ms(); fps_ctrl->frame_time = 0; fps_ctrl->sleep_time = 0; fps_ctrl->frame_count = 0; fps_ctrl->fps = 0; fps_ctrl->last_fps_time = fps_ctrl->last_frame_time; fps_ctrl->call_get_ms = get_ms; fps_ctrl->call_sleep_ms = sleep_ms; } // 帧开始 void ge_fps_begin_frame(ge_fps_controller_t* fps_ctrl) { fps_ctrl->last_frame_time = fps_ctrl->call_get_ms(); } // 帧结束 void ge_fps_end_frame(ge_fps_controller_t* fps_ctrl) { // 计算当前帧耗时 ge_u32_t current_time = fps_ctrl->call_get_ms(); fps_ctrl->frame_time = current_time - fps_ctrl->last_frame_time; // 计算需要休眠的时间 if (fps_ctrl->frame_time < fps_ctrl->frame_duration) { fps_ctrl->sleep_time = fps_ctrl->frame_duration - fps_ctrl->frame_time; // 高精度休眠 fps_ctrl->call_sleep_ms(fps_ctrl->sleep_time); // 更新实际休眠后时间 current_time = fps_ctrl->call_get_ms(); fps_ctrl->sleep_time = current_time - fps_ctrl->last_frame_time - fps_ctrl->frame_time; } else { fps_ctrl->sleep_time = 0; } // 更新FPS计数 fps_ctrl->frame_count++; // 每秒计算一次实际FPS if (current_time - fps_ctrl->last_fps_time >= 1000) { fps_ctrl->fps = fps_ctrl->frame_count; fps_ctrl->frame_count = 0; fps_ctrl->last_fps_time = current_time; } }