How do I measure time in C?

CWindowsWinapiTime

C Problem Overview


I want to find out for how long (approximately) some block of code executes. Something like this:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

How?

C Solutions


Solution 1 - C

You can use the clock method in time.h

Example:

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;

Solution 2 - C

You can use the time.h library, specifically the time and difftime functions:

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );
 
  return 0;
}

(Example adapted from the difftime webpage linked above.)

Please note that this method can only give seconds worth of accuracy - time_t records the seconds since the UNIX epoch (Jan 1st, 1970).

Solution 3 - C

Sometime it's needed to measure astronomical time rather than CPU time (especially this applicable on Linux):

#include <time.h>

double what_time_is_it()
{
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    return now.tv_sec + now.tv_nsec*1e-9;
}

int main() {
    double time = what_time_is_it();
    printf("time taken %.6lf\n", what_time_is_it() - time);
    return 0;
}

Solution 4 - C

GetTickCount().

#include <windows.h>
void MeasureIt()
{
    DWORD dwStartTime = GetTickCount();
    DWORD dwElapsed;

    DoSomethingThatYouWantToTime();

    dwElapsed = GetTickCount() - dwStartTime;

    printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
}

Solution 5 - C

I would use the http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx">QueryPerformanceCounter</a> and http://msdn.microsoft.com/en-us/library/ms644905(VS.85).aspx">QueryPerformanceFrequency</a> functions of the Windows API. Call the former before and after the block and subtract (current − old) to get the number of "ticks" between the instances. Divide this by the value obtained by the latter function to get the duration in seconds.

Solution 6 - C

If you don't need fantastic resolution, you could use GetTickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx (If it's for something other than your own simple diagnostics, then note that this number can wrap around, so you'll need to handle that with a little arithmetic).

QueryPerformanceCounter is another reasonable option. (It's also described on MSDN)

Solution 7 - C

The standard C library provides the time function and it is useful if you only need to compare seconds. If you need millisecond precision, though, the most portable way is to call timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
	struct timespec now;
	timespec_get(&now, TIME_UTC);
	return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
	printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep. This is a useful property for benchmarking and implementing delays that take running time into account.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsnakileView Question on Stackoverflow
Solution 1 - CKLee1View Answer on Stackoverflow
Solution 2 - CStephenView Answer on Stackoverflow
Solution 3 - CIvan TalalaevView Answer on Stackoverflow
Solution 4 - CselbieView Answer on Stackoverflow
Solution 5 - CAndreas RejbrandView Answer on Stackoverflow
Solution 6 - Cuser357501View Answer on Stackoverflow
Solution 7 - CDanielView Answer on Stackoverflow