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.
- Measure execution time of a function in C++
- rand() and srand() in C/C++
- Write your own memcpy() and memmove()
- Multithreading in C
- How to write a running C code without main()?
- Convert a floating point number to string in C
- Print a long int in C using putchar() only
- Implement your own itoa()
- How to change the output of printf() in main() ?
- How to find length of a string without string.h and loop in C?
- Write a C program that does not terminate when Ctrl+C is pressed
- Memory Layout of C Programs
- Print "Even" or "Odd" without using conditional statement
- Implement Your Own sizeof
- Write a C program to print "Geeks for Geeks" without using a semicolon