C programming clock time.h


In C programming the <time.h> clock function calculate the CPU time used by your program.You can use this function to test the execution time of a section of your code in your program or the program as a whole.The declaration of the function is given below.

clock_t clock(void);

Parameters:
void

Return type
clock_t -Returns the implementation’s best approximation to the processor time used by the program.If the function return -1 the CPU time is not available.

Note the basic unit of CPU time is called “tick” and may vary from one system to another.If you want to determine the time in seconds the returned value should be divided by the value of the macro CLOCKS_PER_SEC.

A code example is given below to test the execution time of ‘for’ loop and ‘while’ loop statement.In this program we will loop the ‘for’ and ‘while’ statement 500,000 times and compare the number of ‘ticks’ taken by them.THe first program test the ‘for’ statement.

clock_t end ,
  start = clock() ;

for (int i = 0; i < 500000 ; i++)
{ }

end=clock();

printf(“The number of ticks=%d” , end-start );

Output in VS,

The number of ticks=2

The second program compute the number of ticks in ‘while’ loop statement.

int i =0;
clock_t end ,
  start = clock() ;

while(i=0)
{ i++; }

end=clock();

printf(“The number of ticks=%d” , end-start );

Output in VS,

The number of ticks=2

The output given by the ‘for’ and ‘while’ loop are the same,but note this result may not be accurate so,try looping them for some random number of times and test the output again.