CS21003 Algorithms I
 CS29003 Algorithms Laboratory
Autumn 2011, L-T-P: 3-1-0 
L-T-P: 0-0-3 

How to measure timings in a C program

The prototype example

#include <stdio.h> /* Include standard i/o header file */
#include <time.h>  /* Include the timing header file */

...

clock_t t1, t2;    /* Time variables */
int i,             /* Temporary index */
   repCount;       /* Repetition count */
float timeTaken;   /* Total time taken */

...

repCount = 1000;   /* Set repetition count */

t1 = clock();      /* Record timing before the block begins */

/* Execute the block repCount times */
for (i=0; i<repCount; i++) {
   /* Execute your block here. */ 
}

t2 = clock();     /* Record the time after the block exits */

/* Compute the time taken per execution of the block */
timeTaken = ( (float)(t2 - t1) / (float)CLOCKS_PER_SEC ) / (float)repCount;

printf("Time taken = %f seconds\n", timeTaken);


[Lab home] [Home]