We can calculate the time taken by the process using the clock () function. This function is available in time.h header file.
By calling the clock function at the function start and the end of the code And be follow the below steps to calculate the time taken by the process, please find the pseudo-code.
1 2 3 4 5 6 7 8 9 10 |
#include <time.h> clock_t starttime, endtime; double cpu_time_used; starttime = clock(); // your code block { // statements of your function } endtime = clock(); cpu_time_used = ((double) (endtime - starttime)) / CLOCKS_PER_SEC; |
Following is a sample C program where we measure the time taken by mySampleFunction (). The function mySampleFunction () waits for enter key press to terminate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// 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.
1 2 3 4 5 6 7 |
start of the function Press enter exit from the function mySampleFunction () ends mySampleFunction () tooks 1.473000 seconds to execute |