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?
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.