Wednesday, 3 December 2014

Calculate the time taken by a function in C and explain with example

How to calculate the time taken by a function in C? Please give examples for the same.

We can calculate the time taken by the process using the clock () function. This function is available in
 time.h
header.

By calling the clock function at the function start and the end of the code.
And t be follow the below steps to calculate the time taken by the process, please find the pseudo code.

     #include <time.h>
     clock_t starttime, endtime;
     double cpu_time_used;
     starttime = clock();
// your code bloc
{
// statements of your function
}
     endtime = clock();
     cpu_time_used = ((double) (endtime - starttime)) / CLOCKS_PER_SEC;

Following is a sample C program where we measure time taken by mySampleFunction (). The function mySampleFunction () waits for enter key press to terminate.
// A function that terminates when enter key is pressed
void mySampleFunction()
{
    printf("start of the function \n");
    printf("Press enter exit from the function\n");
    while(1)
    {
        if (getchar ())
            break;
    }
    printf("mySampleFunction () ends \n");
}
int main()
{
    clock_t tickStart;
    tickStart = clock();
    mySampleFunction ();
   tickStart = clock() - tickStart;
   double Total_Time = ((double)tickStart) / CLOCKS_PER_SEC;
    printf("mySampleFunction () tooks %f seconds to execute \n", Total_Time);
    getchar ();
    return 0;
}
The output of  the above program is.
start of the function

Press enter exit from the function

mySampleFunction () ends

mySampleFunction () tooks 1.393000 seconds to execute


No comments: