VocExile/Progrmming Topics/Measuring Execution Time

Measuring Execution Time of C Code

The C code shown below demonstrates a simple way that a programmer can measure the approximate time that a specific code segment takes to execute. It calls the clock() function before and after the specified program segment, and subtracts the difference.

The macro CLK_TCK is defined in time.lib. It equals the number of clock ticks per second. For a PC it is 100. Multiplying the number of ticks by the variable ratio causes the time to be measured in milliseconds. The program measures time to the nearest ten milliseconds.



#include stdio.h
#include time.h

void main(void);

void main()
{
long i;
long ratio;
clock_t time1;
clock_t time2;

ratio = 1000/CLK_TCK;

/* MEASURE THE TIME TO EXECUTE A FOR LOOP */
time1 = clock(); for (i = 0; i < 1000000; i++); time2 = clock(); /* END OF TIME MEASUREMENT */

printf("\nThis program segment took %ld milliseconds to execute.", ratio * (long)time2 - ratio * (long)time1 );
}



The program measures the length of time needed to execute a simple for loop with one million iterations. On a 386 SX PC with a microprocessor speed of 20 MHz, the loop required 11,700 milliseconds to execute. On a 686 (similar to a Pentium II) 233 MHz computer, it took 160 milliseconds.


Back to Programming Menu.

Back to Main Menu.


http://www.nfinity.com/~exile/progmenu/time
Email: See bottom of Programming Menu
Date last updated: March 30, 1999