How do I measure time in C?

Solution 1:

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:

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:

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;
}