Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to measure time taken by a function in C?
Here we will see how to calculate the time taken by a process or function in C. For this problem, we will use the clock() function. The clock() function is present in the time.h header file.
To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCKS_PER_SEC (Number of clock ticks per second) to get the processor time.
Syntax
clock_t clock(void);
Example
Here's a complete example that measures the time taken by a function −
#include <stdio.h>
#include <time.h>
void take_enter() {
printf("Press enter to stop the counter<br>");
while(1) {
if (getchar())
break;
}
}
int main() {
// Calculate the time taken by take_enter()
clock_t t;
t = clock();
printf("Timer starts<br>");
take_enter();
printf("Timer ends<br>");
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
printf("The program took %f seconds to execute<br>", time_taken);
return 0;
}
Output
Timer starts Press enter to stop the counter Timer ends The program took 5.218000 seconds to execute
Key Points
- The
clock()function returns the processor time consumed by the program. -
CLOCKS_PER_SECis a constant that defines the number of clock ticks per second. - Always cast the result to
doublefor accurate fractional seconds. - This method measures CPU time, not wall-clock time.
Conclusion
The clock() function provides an easy way to measure execution time in C programs. By taking timestamps before and after function calls, you can accurately measure performance and optimize your code.
