I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.
I use code the following code to do this. (import before)
clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
However for small inputs or short statements such as a = a + 1, I get "0 seconds" result. I think it must be something like 0.0000001 seconds or something like that.
I remember that System.nanoTime()
in Java works pretty well in this case. However I can't get same exact functionality from clock()
function of C++.
Do you have a solution?
boost::timer will probably give you as much accuracy as you'll need. It's nowhere near accurate enough to tell you how long
a = a+1;
will take, but I what reason would you have to time something that takes a couple nanoseconds?I created a simple utility for measuring performance of blocks of code, using the chrono library's high_resolution_clock: https://github.com/nfergu/codetimer.
Timings can be recorded against different keys, and an aggregated view of the timings for each key can be displayed.
Usage is as follows:
Here is a simple solution in C++11 which gives you satisfying resolution.
Or on *nix, for c++03
Here is the example usage:
From https://gist.github.com/gongzhitaao/7062087
(windows specific solution) The current (circa 2017) way to get accurate timings under windows is to use "QueryPerformanceCounter". This approach has the benefit of giving very accurate results and is recommended by MS. Just plop the code blob into a new console app to get a working sample. There is a lengthy discussion here: Acquiring High resolution time stamps
When
progress_timer
goes out of scope it will print out the time elapsed since its creation.UPDATE: I made a simple standalone replacement (OSX/iOS but easy to port): https://github.com/catnapgames/TestTimerScoped
Windows provides QueryPerformanceCounter() function, and Unix has gettimeofday() Both functions can measure at least 1 micro-second difference.