Published on

Executing Processing at Regular Intervals in C++

Authors

At work I wrote a program that performs processing at fixed intervals. When the processing time varies to some degree, it waits until the next integer multiple of the interval before running again. I used Boost.Chrono's high_resolution_clock because it offers high precision for measuring the processing time.

#include <iostream>

#include <boost/chrono.hpp>
#include <boost/random.hpp>
#include <boost/thread.hpp>
#include <boost/timer/timer.hpp>

void measure()
{
  boost::random::mt19937 gen;
  boost::random::uniform_int_distribution<> dist(1000, 1800);
  boost::this_thread::sleep_for(boost::chrono::milliseconds(dist(gen)));
}

int main()
{
  using namespace boost;

  long long interval_ns = 2 * 1000 * 1000 * 1000;

  chrono::high_resolution_clock::time_point start, end;
  for (int i = 0; i < 10; i++) {
    timer::cpu_timer t;
    start = chrono::high_resolution_clock::now();

    measure();

    end = chrono::high_resolution_clock::now();

    chrono::nanoseconds actual_interval_ns = end - start;

    long long ns = actual_interval_ns.count();
    int num_interval = ns /interval_ns;

    this_thread::sleep_for(chrono::nanoseconds((num_interval + 1) * interval_ns - ns));
    std::cout << t.elapsed().wall / 1000000.0 << std::endl;
  }

  return 0;
}