You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同一OpenGL可执行文件在CLion与CMD中浮点输出不一致,CMD显示inf

问题描述

同一OpenGL可执行文件在CLion和CMD中运行输出不一致:CLion显示正确FPS数值,CMD中有时输出inf,有时显示正常数值,使用cout输出也存在同样问题(已移除所有不必要的OpenGL调用)。

相关代码片段:

int i = 0;
auto lastTime = std::chrono::high_resolution_clock::now();
while (...) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    if (i % 10000 == 0) {
        auto deltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(currentTime - lastTime).count();
        printf("FPS: %10.0f\n", 1.0f / deltaTime);
    }
    i++;
    lastTime = currentTime;
}

(注:截图左侧为CLion输出,右侧为CMD输出)

问题原因

核心问题出在**deltaTime可能为0**:

  • std::chrono::high_resolution_clock的精度依赖系统和运行环境,当循环执行速度极快时,currentTime和lastTime可能完全相同,导致时间差为0。
  • CLion运行时通常附加调试环境,程序执行速度相对较慢,两次时间采样的间隔足以产生非零的deltaTime;而CMD中程序以Release模式运行(或无调试附加),循环执行更快,容易出现时间差为0的情况,此时1.0f / 0就会得到inf。
解决方法
  • 增加时间差检查:计算FPS前先判断deltaTime是否大于0,避免除以0的情况:
if (i % 10000 == 0) {
    auto deltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(currentTime - lastTime).count();
    if (deltaTime > 0.0f) {
        printf("FPS: %10.0f\n", 1.0f / deltaTime);
    } else {
        printf("FPS:   Too fast\n"); // 或输出合理默认值
    }
}
  • 调整采样间隔:改为固定时间间隔采样(比如每0.5秒计算一次FPS),避免因循环过快导致时间差为0:
auto lastTime = std::chrono::high_resolution_clock::now();
int frameCount = 0;
while (...) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    frameCount++;
    auto elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(currentTime - lastTime).count();
    if (elapsed >= 0.5f) {
        float fps = frameCount / elapsed;
        printf("FPS: %10.0f\n", fps);
        frameCount = 0;
        lastTime = currentTime;
    }
}
  • 提升时间精度存储:用double替代float存储时间差,减少精度丢失,但仍需配合检查逻辑,无法完全避免极端情况。

内容的提问来源于stack exchange,提问作者kek5chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:15:35