Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: High-Resolution Timer

📅 2011-Apr-08 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, timer ⬩ 📚 Archive

Timers are useful to find the performance bottlenecks in code. If a timer resolution of 1ms is enough for your application, you can use the clock function from <ctime> as shown here.

However, if you need timers of a far higher resolution on Windows, a popular choice is to use the high-resolution performance counter API. All calls of this API rely on a LARGE_INTEGER data type.

Use QueryPerformanceCounter to note down the begin and end times of your code:

#include <windows.h>

QueryPerformanceCounter( &beginTime );

// Code to measure ...

QueryPerformanceCounter( &endTime );

Use QueryPerformanceFrequency to find the timer frequency. Use that to convert the time difference to seconds:

QueryPerformanceFrequency( &timerFreq );
const double freq = 1.0f / timerFreq.QuadPart;

const double timeSeconds = ( endTime.QuadPart - beginTime.QuadPart ) * freq;

A PerfTimer class that exposes this as simple start(), stop() and value() calls is available here.

Tried with: Visual C++ 2008

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧