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?
I suggest using the standard library functions for obtaining time information from the system.
If you want finer resolution, perform more execution iterations. Instead of running the program once and obtaining samples, run it 1000 times or more.
You can use this function I wrote. You call
GetTimeMs64()
, and it returns the number of milliseconds elapsed since the unix epoch using the system clock - the just liketime(NULL)
, except in milliseconds.It works on both windows and linux; it is thread safe.
Note that the granularity is 15 ms on windows; on linux it is implementation dependent, but it usually 15 ms as well.
You could also look at the
[cxx-rtimers][1]
on GitHub, which provide some header-only routines for gathering statistics on the run-time of any code-block where you can create a local variable. Those timers have versions that use std::chrono on C++11, or timers from the Boost library, or standard POSIX timer functions. These timers will report the average, maximum & minimum duration spent within a function, as well as the number of times it is called. They can be used as simply as follows:just a simple class that benchmark the codeblock :
In some programs I wrote I used RDTS for such purpose. RDTSC is not about time but about number of cycles from processor start. You have to calibrate it on your system to get a result in second, but it's really handy when you want to evaluate performance, it's even better to use number of cycles directly without trying to change them back to seconds.
(link above is to a french wikipedia page, but it has C++ code samples, english version is here)
For cases where you want to time the same stretch of code every time it gets executed (e.g. for profiling code that you think might be a bottleneck), here is a wrapper around (a slight modification to) Andreas Bonini's function that I find useful: