benchmarking - How to Calculate Execution Time of a Code Snippet in C++ -


I want to calculate the execution time of the C ++ code snippet in seconds, either working on Windows or Unix machines is.

I use the code to do this following code. (Import first)

  clock_t startTime = clock (); // some code here // to calculate its execution period in runtime Cout & lt; & Lt; Double (clock () - start time) / (double) CLOCKS_PER_SEC & lt; & Lt; "Seconds." & Lt; & Lt; Endl;  

Although small input or short statement such as = a + 1, I get a "0 second" result, I think such a thing should be 0.0000001 seconds or something like that.

I remember that system.nanoTime () in Java works very well in this case. However, I can not get the same exact functionality from the function of clock () C ++

Do you have any solutions?

You can use this function, you can write I GetTimeMs64 () , and it uses the system clock to give the number of milliseconds since the Unix era - such as time (zero) , in milliseconds.

It works on both Windows and Linux; This thread is safe.

Note that granulity is at 15 meters windows; This implementation depends on Linux, but it is usually also 15 ms.

  #ifdef _WIN32 #include & lt; Windows.h & gt; #else #include & lt; Sys / time.h & gt; # Include & lt; Ctime & gt; #endif / * If pre-defined then / typedef long long int64; Typedef unsigned long uint64; / * Returns the amount of milliseconds found after the UNIX era * Works on both windows and linux * / Uint64 GetTimeMs64 () {#ifdef _WIN32 / * Windows * / FILETIME ft; LARGE_INTEGER li; Get the amount of intervals of 100 nanoseconds passed on 1 January 1, 1601 (UTC) and copy it into a large_intgER structure. * / GetSystemTimeAsFileTime (and FT); Li.LowPart = ft.dwLowDateTime; Li.HighPart = ft.dwHighDateTime; Uint64 ret = li.QuadPart; Write - = 116444736000000000 LL; / * Change time of UNIX era from file time * / rate / = 10000; 1 * millisecond (10 ^ -3) interval * / return by 100 nanose seconds (10 ^ -7); #els / * linux * / strat timewave tv; Gettimeofday (& amp; TV, NULL); Uint64 ret = tv.tv_usec; / * Change from Micro seconds (10 ^ -6) to milliseconds (10 ^ -3) * / rate / = 1000; After converting / * seconds (10 ^ 0) to milliseconds (10 ^ -3) * / rate + = (TV. Tv_sec * 1000); Return writ; #endif}  

Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -