opengl-tutorials / ogl

http://www.opengl-tutorial.org
2.69k stars 925 forks source link

Time correctness in FPS counter #89

Open IGR2014 opened 5 years ago

IGR2014 commented 5 years ago

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!

https://github.com/opengl-tutorials/ogl/blob/316cccc5f76f47f09c16089d98be284b689e057d/tutorial09_vbo_indexing/tutorial09.cpp#L137-L151

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.