High-resolution timer for C++

Howdy ho! My name is Simon Wybranski, I am a developer on the C++ AMP team!

In this blog post I am going to present a high-resolution timer for measuring the performance of C++ AMP algorithms. There is nothing specific in it to C++ AMP, so it can be used to measure elapsed time of your PPL algorithms or any other C++ code.

Listing of timer.h:

  1: #pragma once
  2: #include <windows.h>
  3:  
  4: struct Timer
  5: {
  6:     void Start() 
  7:     {
  8:         QueryPerformanceCounter(&m_start);
  9:     }
  10:  
  11:     void Stop() 
  12:     {
  13:         QueryPerformanceCounter(&m_stop);
  14:     }
  15:     
  16:     // Returns elapsed time in milliseconds (ms)
  17:     double Elapsed()
  18:     {
  19:         return (m_stop.QuadPart - m_start.QuadPart - m_overhead) \
  20:                                           * 1000.0 / m_freq.QuadPart;
  21:     }
  22:  
  23: private:
  24:  
  25:     // Returns the overhead of the timer in ticks
  26:     static LONGLONG GetOverhead()
  27:     {
  28:         Timer t;
  29:         t.Start();
  30:         t.Stop();
  31:         return t.m_stop.QuadPart - t.m_start.QuadPart;
  32:     }
  33:  
  34:     LARGE_INTEGER m_start;
  35:     LARGE_INTEGER m_stop;
  36:     static LARGE_INTEGER m_freq;
  37:     static LONGLONG m_overhead;
  38: };

 

Listing of timer.cpp:

  1: #include "timer.h"
  2:  
  3: // Initialize the resolution of the timer
  4: LARGE_INTEGER Timer::m_freq = \
  5:           (QueryPerformanceFrequency(&Timer::m_freq), Timer::m_freq);
  6:  
  7: // Calculate the overhead of the timer
  8: LONGLONG Timer::m_overhead = Timer::GetOverhead();

 

Snippet showing the usage:

  1: Timer t; 
  2: t.Start(); 
  3: // Your algorithm goes here 
  4: t.Stop(); 
  5:  
  6: std::cout << t.Elapsed() << " ms" << std::endl; 

 

Enjoy!!

timer.zip