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?