Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Timing the code

📅 2010-May-25 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, timers ⬩ 📚 Archive

Timing C++ code is easy using the clock function call from the <ctime> header file:

#include <ctime>
clock_t begin = clock();
doSomething();
clock_t end = clock();
double timeSec = (end - begin) / static_cast<double>( CLOCKS_PER_SEC );

CLOCKS_PER_SEC is typically defined as 1000 in most C++ library implementations. So, the clock resolution is typically 1 millisecond.

If you need higher resolution timing on Windows, check out the high-resolution performance counter described here.

Tried with: Visual C++ 2008