Walker Walker - 2 months ago 10
C Question

C - execution time of program in millseconds using <time.h>

I'm trying to get the execution time of my program using the time header and can't find any resources that simply use

<time.h>
and not
<sys/time.h>
.

I tried

time_t startTime;
time_t endTime;
long double execTime;

/* Start timer */
time(&startTime);

..STUFF THAT TAKES TIME..

time(&endTime);
execTime = difftime(endTime, startTime);

printf("Computing took %Lf\n", execTime * 1000);


But this prints out 0 every single time.. I'm guessing because time is an integer and my process takes less than a second.

How can I show execution in milliseconds?

Thank you

Answer

Although clock_gettime should be the preferred way, it is Posix, not standard C. They have only clock. It has a lot of disadvantages but is good enough for a quick and dirty measurement.

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

int main()
{
  int i, j, a[1000000] = { 0 };
  clock_t start, stop;
  srand(0xdeadbeef);
  start = clock();
  // play around with these values, especially with j
  for (j = 0; j < 100; j++) {
    for (i = 0; i < 1000000; i++) {
      a[i] = rand() % 123;
      a[i] += 123;
    }
  }
  stop = clock();
  printf("Time %.10f seconds\n", (double) (stop - start) / CLOCKS_PER_SEC);
  exit(EXIT_SUCCESS);
}
Comments