Walker Walker - 1 year ago 57
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

and not

I tried

time_t startTime;
time_t endTime;
long double execTime;

/* Start timer */


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 Source

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;
  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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download