VocExile/Progrmming Topics/Measuring Execution Time
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.
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.