Friday, August 26, 2011

How to measure timings in a C program

Include the header file
Time variables have data type clock_t. 
If you want to measure the timimg of a block, note the time t1 just before the block begins and the time t2 just after the block exits. Use the C library call clock() to know a particular time. 
Divide (t2 - t1) by CLOCKS_PER_SEC to get the number of seconds the block took. 
If the block returns too fast so that you get a zero time, repeat the block some number of times (say, 100 or 1000 or ...) and record the timing for these many executions of the block. 
The prototype example
#include /* Include standard i/o header file */
#include  /* 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

0 comments:

Post a Comment