To calculate time taken by a process, we can use clock() function which is available time.h. We can call the clock function at the beginning and end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like following.
#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;
Following is a sample C program where we measure time taken by fun(). The function fun() waits for enter key press to terminate.
Output: The following output is obtained after waiting for around 4 seconds and then hitting enter key.
fun() starts Press enter to stop fun fun() ends fun() took 4.017000 seconds to execute
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Measure execution time of a function in C++
- Measure execution time with high precision in C/C++
- time() function in C
- time.h localtime() function in C with Examples
- Time delay in C
- time.h header file in C with Examples
- Print system time in C++ (3 different ways)
- RTTI (Run-time type Information) in C++
- C++ Program to print current Day, Date and Time
- Finding Median of unsorted Array in linear time using C++ STL
- C program to print digital clock with current time
- Cvent Interview Experience (On campus for Internship and Full Time)
- Amadeus Labs R & D | On Campus (freshers) | Full time+Internship
- Program to convert time from 12 hour to 24 hour format
- Function Overloading vs Function Overriding in C++
- How to call function within function in C or C++
- What happens when a virtual function is called inside a non-virtual function in C++
- Difference between Virtual function and Pure virtual function in C++
- fma() function in C++
- div() function in C++