- Write a program in C to calculate the execution time of a program in seconds.
- How to find the time taken by a function or statement to execute in C.
To find the execution time of a C program, we will use clock() function of time.h header file.
- clock() function returns the number of clock ticks elapsed since the program started.
- To find the total execution time of a program we will call clock function twice, once at the beginning of main function and then again at the end of main function.
- Now, the total execution time of a program(in units of cpu clock ticks) is the difference between these two time instances.
- To get the execution time in seconds, we will need to divide the difference by CLOCKS_PER_SEC(the number of clock ticks per second).
Placement of clock() function to find execution time of C program
# include<stdio.h> # include<time.h> int main() { clock_t start, end; double execution_time; start = clock(); /* Put your code here */ end = clock(); execution_time = ((double)(end - start))/CLOCKS_PER_SEC;
C program to find execution time of a program
#include <stdio.h> #include <time.h> int main() { clock_t start, end; /* Store start time here */ start = clock(); /* put the main body of your program here */ printf("Enter any character\n"); getchar(); /* program logic ends here */ end = clock(); /* Get the time taken by program to execute in seconds */ double duration = ((double)end - start)/CLOCKS_PER_SEC; printf("Time taken to execute in seconds : %f", duration); return 0; }
Output
Enter any character d Time taken to execute in seconds : 2.371000
C program to find execution time of a functionn
#include <stdio.h> #include <time.h> void my_function(){ /* Body of function */ float f; for(f=0.0; f<1000000; f=f+1.0); } int main() { clock_t start, end; /* Store time before function call */ start = clock(); my_function(); /* Store time after function call */ end = clock(); /* Get the time taken by program to execute in seconds */ double duration = ((double)end - start)/CLOCKS_PER_SEC; printf("Time taken to execute in seconds : %f", duration); return 0; }
Output
Time taken to execute in seconds : 0.015000