Measure Time taken By A Function In C


To get a process’ CPU time, we can use the clock function. This facility is declared in the header file time.h.
we call the clock function at the beginning and end of the interval we want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like this:


#include <time.h>

clock_t start, end;
double cpu_time_used;

start = clock();
… /* Do the work. */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

Example :

#include<stdio.h>
#include<time.h>

void fun()
{
 int i;
 
 printf("\nProcess start...\n");
 while(1)
 {
  printf("\nHello World !!");
     if(getchar())
     break;
 }
 printf("\nProcess end..");
}
int main()
{
 clock_t t;
 double cpu_time_used;
 
 printf("\nPress Enter for termination....\n");
 
 t=clock();
 fun();
 t=clock()-t;
 
 cpu_time_used=((double)t/CLOCKS_PER_SEC);
 printf("\n\nTime in seconds to execute :%f",cpu_time_used);
 
 getch();
 return 0;
}

Output :


No comments: