2
#include <cstdio>

#include "boost/date_time/posix_time/posix_time.hpp"

int main(int argc, char** argv) {
  boost::posix_time::ptime start =
      boost::posix_time::microsec_clock::local_time();

  uint32_t iterations = 0;

  // Do a bunch of work. `iterations` becomes > 0

  boost::posix_time::ptime now =
     boost::posix_time::microsec_clock::local_time();
  boost::posix_time::time_duration diff = now - start;
  printf("Milliseconds per iteration: %f\n",
      static_cast<float>(diff.total_milliseconds()) / iterations);

  return 0;
}

This printed out a negative value. How can this be?

1 Answers1

4

Using boost::posix_time::microsec_clock::local_time() to measure a time difference while daylight savings goes out of effect can result in the described behaviour.

If start is set to 01:59:59.345 and the program takes 1 second to do it's stuff (during which, daylight savings goes out of effect), now would be set to 01:00:00.345.

You should use boost::posix_time::microsec_clock::universal_time() to avoid this issue.

(Related: Daylight saving time and time zone best practices)

Community
  • 1
  • 1