setting the execution rate of while loop in a C++ code for real time synchronization
Simple and accurate solution with std::this_thread::sleep_until
:
#include "date.h"
#include <chrono>
#include <iostream>
#include <thread>
int
main()
{
using namespace std::chrono;
using namespace date;
auto next = steady_clock::now();
auto prev = next - 200ms;
while (true)
{
// do stuff
auto now = steady_clock::now();
std::cout << round<milliseconds>(now - prev) << '\n';
prev = now;
// delay until time to iterate again
next += 200ms;
std::this_thread::sleep_until(next);
}
}
"date.h"
isn't needed for the delay part. It is there to provide the round<duration>
function (which is now in C++17), and to make it easier to print out duration
s. This is all under "do stuff", and doesn't matter for the loop delay.
Just get a chrono::time_point
, add your delay to it, and sleep until that time_point
. Your loop will on average stay true to your delay, as long as your "stuff" takes less time than your delay. No other thread needed. No timer needed. Just <chrono>
and sleep_until
.
This example just output for me:
200ms
205ms
200ms
195ms
205ms
198ms
202ms
199ms
196ms
203ms
...