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
- Include the header file <time.h>.
- 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 <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);