5

I am curious if there is a build-in function in C++ for measuring the execution time? I am using Windows at the moment. In Linux it's pretty easy...

CppLearner
  • 16,273
  • 32
  • 108
  • 163

6 Answers6

4

The best way on Windows, as far as I know, is to use QueryPerformanceCounter and QueryPerformanceFrequency.

QueryPerformanceCounter(LARGE_INTEGER*) places the performance counter's value into the LARGE_INTEGER passed.

QueryPerformanceFrequency(LARGE_INTEGER*) places the frequency the performance counter is incremented into the LARGE_INTEGER passed.

You can then find the execution time by recording the counter as execution starts, and then recording the counter when execution finishes. Subtract the start from the end to get the counter's change, then divide by the frequency to get the time in seconds.

LARGE_INTEGER start, finish, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
// Do something
QueryPerformanceCounter(&finish);
std::cout << "Execution took " 
    << ((finish.QuadPart - start.QuadPart) / (double)freq.QuadPart) << std::endl;
Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
2

It's pretty easy under Windows too - in fact it's the same function on both std::clock, defined in <ctime>

2

You can use the Windows API Function GetTickCount() and compare the values at start and end. Resolution is in the 16 ms ballpark. If for some reason you need more fine-grained timings, you'll need to look at QueryPerformanceCounter.

Nicholas M T Elliott
  • 3,643
  • 2
  • 19
  • 15
1

C++ has no built-in functions for high-granularity measuring code execution time, you have to resort to platform-specific code. For Windows try QueryPerformanceCounter: http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx

Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
1

The functions you should use depend on the resolution of timer you need. Some of them give 10ms resolutions. Those functions are easier to use. Others require more work, but give much higher resolution (and might cause you some headaches in some environments. Your dev machine might work fine, though).

http://www.geisswerks.com/ryan/FAQS/timing.html

This articles mentions:

  • timeGetTime
  • RDTSC (a processor feature, not an OS feature)
  • QueryPerformanceCounter
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
0

C++ works on many platforms. Why not use something that also works on many platforms, such as the Boost libraries.

Look at the documentation for the Boost Timer Library

I believe that it is a header-only library, which means that it is simple to setup and use...

Demi
  • 6,147
  • 7
  • 36
  • 38