Hi I have a working loop that tries to iterate at a fixed frequency. In reality it's more like the max frequency since there can be slow downs. but here it is:
void FixedFrequencyLoop::start(const std::function<void(double)> &rate_limited_func,
const std::function<bool()> &termination_condition_func,
std::function<void(IterationStats)> loop_stats_function) {
auto period_ns = std::chrono::nanoseconds{static_cast<long long>(1'000'000'000.0 / max_update_rate_hz)};
auto loop_start_time = std::chrono::steady_clock::now();
auto time_at_start_of_last_iteration = loop_start_time;
double total_time = 0.0;
int count = 0;
bool should_keep_running = true;
while (should_keep_running) {
GlobalLogSection _("ffl while loop", logging_enabled);
auto current_time = std::chrono::steady_clock::now();
auto elapsed = current_time - time_at_start_of_last_iteration;
time_at_start_of_last_iteration = current_time;
double measured_period = std::chrono::duration<double>(elapsed).count();
total_time += measured_period;
++count;
rate_limited_func(measured_period);
if (rate_limiter_enabled) {
GlobalLogSection _("sleep", logging_enabled);
auto next_target_time = loop_start_time + period_ns * count;
auto now = std::chrono::steady_clock::now();
if (next_target_time > now) {
std::this_thread::sleep_until(next_target_time);
} else {
// we're behind schedule, skip sleep to catch up
}
}
should_keep_running = !termination_condition_func();
iteration_count++;
}
}