0

I have a project wherein I want to have a continually running loop that keeps track of the delta time from one cycle to the next. After looking into solutions I decided on the chrono library, but I am noticing some behavior I was not expecting.

Here is the code:

#include<iostream>
#include<chrono>

using namespace std;
using namespace std::chrono;

int main(int argc, char* argv[])
{
    // Testing chrono
    auto current = chrono::high_resolution_clock::now();
    auto prev = chrono::high_resolution_clock::now();

    auto delta = chrono::nanoseconds{current - prev};
    auto timer = std::chrono::nanoseconds{3};

    cout<< "Start Loop" << endl;

    while(true)
    {
        current = chrono::high_resolution_clock::now();
        delta = chrono::nanoseconds{current - prev};

        // // Timer has been count down
        if(timer <= chrono::nanoseconds::zero())
        {
            // set new timer
            timer = chrono::seconds{3};
            cout << "Timer complete! New time: " << timer.count() <<endl;

        } else {
            // Decrement timer
            timer = std::chrono::nanoseconds {timer - delta};
        }
        


        prev = chrono::high_resolution_clock::now();
    }
    return 0;
}

I have measured the execution time using an external clock to see how often the console message is printed out, and it is almost twice as long as the specified time it is set to once it finishes counting down (around ~6.5 seconds).

Am I using the chrono library incorrectly here, or is there something else I am missing?

  • I'm guessing you're on windows, the console is verrrry slow and is likely the cause of your discrepancy, also make sure you're using optimised code, heavily templated code like chrono can be quite slow in debug mode. changing `prev = chrono::high_resolution_clock::now();` to `prev = current;` should improve accuracy – Alan Birtles Mar 07 '23 at 18:16
  • FWIW, the creator of `chrono::high_resolution_clock` recommends you no longer use it: https://stackoverflow.com/questions/37426832/what-are-the-uses-of-stdchronohigh-resolution-clock – NathanOliver Mar 07 '23 at 18:28
  • After optimizing the code, and swapping out `chrono::high_resolution_clock` for `chrono::steady_clock`. I have gotten down the execution time to nearly the exact specified time. I am running on Windows and a WSL setup to compare execution time. Thanks to @AlanBirtles and @NathanOliver for your assistance in solving my problem! – Senuska Mar 07 '23 at 19:01

0 Answers0