2

What would be a good way to measure sub-second elapsed time of native C++ code on Windows Platform(I am working on Windows Vista, Visual Studio 2010)

I have tried using

#include <ctime>

int main()
{    
    clock_t start = clock();
    ... some code
    clock_t end = clock();
    double cpu_time = static_cast<double>(end - start)/CLOCKS_PER_SEC;
}

but cpu_time is always 0.

Thanks !

newprint
  • 6,936
  • 13
  • 67
  • 109
  • 2
    You could try putting the `some code` in a loop and then dividing? Also, try just printing out `end` and `start` and see if they're different at all. – Xymostech Nov 25 '12 at 23:17
  • @chris I have copy of Windows 7 and Visual Studio 2012, will give a try. – newprint Nov 25 '12 at 23:22
  • 1
    For older toolsets there is also [Boost.Chrono](http://www.boost.org/libs/chrono/). – ildjarn Nov 26 '12 at 00:55
  • @newprint, If you're still trying to use/understand it, I remember giving a timer example [here](http://stackoverflow.com/questions/13390620/alternatives-to-ctime/13390783#13390783), not too long ago. – chris Nov 26 '12 at 01:20
  • [duplicate](http://stackoverflow.com/questions/13469715/c-fine-granular-time/13471487#13471487) – Arno Nov 26 '12 at 07:40

2 Answers2

2

You can use the QueryPerformanceFrequency and QueryPerformanceCounter WinAPI functions. Example

Community
  • 1
  • 1
kol
  • 27,881
  • 12
  • 83
  • 120
0

Your code is all valid and working. If you're trying to time the execution of a particular piece of code, you should run it through a loop, as suggested by Xymostech. The main reason being:

  • Your code snippet will execute very fast. In some cases, executing the start, code-snippet, and end of your timer the same clock-tick. This will result in start holding the same value as end, causing cpu_time to equal zero.

however, there is also the added benefit of being able to calculate the average execution time over many iterations

Logan Besecker
  • 2,733
  • 4
  • 23
  • 21