1

I'm trying to create a as-steady-as-possible update loop using std::chrono. I came up with the following implementation and profiled the actual update/frame durations:

bool firstUpdate = true;
std::chrono::time_point<std::chrono::steady_clock> lastUpdateTime;
std::chrono::time_point<std::chrono::steady_clock> lastUpdateProf;

while (true)
{
    if (firstUpdate)
    {
        lastUpdateTime = std::chrono::steady_clock::now();
        firstUpdate = false;
    }

    lastUpdateTime = lastUpdateTime + std::chrono::milliseconds(100);

    // Do the work, generate data and send data
    ....

    // Sleep if necessary 
    std::this_thread::sleep_until(lastUpdateTime);

    // Additional profiling of frame duration
    auto now = std::chrono::steady_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(now - lastUpdateProf).count() << std::endl;
    lastUpdateProf = now;
}

Here are the measured number of milliseconds per update for a couple of frames:

98 99 99 101 99 100 99 100 98 100 99 100 99 101 99 99 102 99 100 99 98

I am aware that on my non-realtime platform (Windows 10, 64 bit, VS2017) the update rates are not perfect, but are these results (+/- 2ms jitter) out-of-the-ordinary, or something that can be expected on a non-realtime platform? Or is there a bug in my code?

Regards,

Ben

Ben
  • 1,519
  • 23
  • 39
  • `sleep_until` sleeps until at least the time given, on windows you'd normally only get 15ms accuracy unless something has called [`timeBeginPeriod `](https://learn.microsoft.com/en-us/windows/win32/api/timeapi/nf-timeapi-timebeginperiod) – Alan Birtles Aug 26 '21 at 12:13

0 Answers0