opengl-tutorials/ogl

Time correctness in FPS counter

IGR2014 opened this issue · 0 comments

Good day to you. Found an issue. Right here it looks like time calculations are wrong - you calculate actual time difference but in calculations below you assume it equals to exacly 1 second which is wrong for real world. You should use actual time difference instead of 1 second or 1000 milliseconds. Also, glfwGetTime() according to docs returns time in seconds, not milliseconds!

double lastTime = glfwGetTime();
int nbFrames = 0;
do{
// Measure speed
double currentTime = glfwGetTime();
nbFrames++;
if ( currentTime - lastTime >= 1.0 ){ // If last prinf() was more than 1sec ago
// printf and reset
printf("%f ms/frame\n", 1000.0/double(nbFrames));
nbFrames = 0;
lastTime += 1.0;
}

Should't there be something like this?

auto lastTime = std::chrono::high_resolution_clock::now();
int nbFrames = 0;
do{
    // Measure speed
    auto currentTime = std::chrono::high_resolution_clock::now();
    nbFrames++;
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    if ( currentTime - lastTime >= std::chrono::seconds(1) ){ // If last prinf() was more than 1 sec ago
        auto timeDiff = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - lastTime);
         // printf and reset timer
        std::cout << timeDiff.count() / double(nbFrames) << " ms/frame\n" << std::endl;
        nbFrames = 0;
        lastTime += timeDiff;
    }
    // ... rest of the main loop

Also please, note that glfwGetTime() returns time in seconds according to this

P.S.
I used c++11 just to demonstrate one of possible concepts how it could be (sorry, just more familiar with c++11). Will then rewrite in C-style if needed.