Skip to content

How to record elaspsed wall time in C?

An answer to this question on Stack Overflow.

Question

I'm trying to record the time my program takes to finish in seconds, with sub-second accuracy.

I'm not recording CPU time or cycles, I simply want to be able to mark a start point (Wall Clock time), then at the end of my program mark a finish (Wall Clock time), and calculate the delta.

Answer

You can use the clock() function to record the number of ticks taken and then convert this to seconds:

#include <time.h>
#include <stdio.h>
#include <math.h>
int main () {
   clock_t start_t = clock();
    
   double a=0;
   for(int i=0; i< 10000000; i++) {
     a+=sqrt(a);
   }
   clock_t end_t = clock();
   
   double total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total time taken by CPU: %lf\n", total_t  );
   return(0);
}