Quality Assurance - Time Measurement for C++

Time measurement can be used as poor-man profiler / optimization option. Sometimes process is very long or you need just to measure one function. Profiler slows down the execution of process or you need execution time to compare results of optimization. In this case measuring time using self-inserted time measuring code can be more handy than profiler.


1) C++11 std::chrono, boost::chrono

2) clock() function (for C/C++)

#include <time.h>
clock_t startTime = clock();
// --> perform processing
// <--
clock_t endTime = clock();
clock_t totalTicks = endTime - startTime;
double timeInSeconds = totalTicks / (double) CLOCKS_PER_SEC;

3) Win32 QueryPerformanceCounter - just use:

/// Return current time in CPU clock ticks 
unsigned long long cpu_time_ticks()
  QueryPerformanceCounter(&watch) ;
  return watch.QuadPart;

/// Convert CPU clock ticks to milliseconds
unsigned long long cpu_time_ticks_to_ms(long long ticks)
  double res;
  LARGE_INTEGER frequency;
  QueryPerformanceFrequency( &frequency );
  res = (static_cast<double>(ticks) /static_cast<double>(frequency.QuadPart));
  res *= 1000.0;
  return static_cast<unsigned long long>(res);

4) High-performance Timing on Linux / Windows - Tom Distler, 2010

See also