clock() Function
The clock()
function in C time.h returns the processor time consumed by the program. It is a useful tool for measuring the execution time of code segments by providing the elapsed clock ticks, which can be converted to seconds using CLOCKS_PER_SEC
.
Syntax of clock()
clock_t clock(void);
Parameters
Parameter | Description |
---|---|
None | This function does not require any parameters. |
The value returned by clock()
represents the number of clock ticks elapsed since a system-specific epoch related to the program’s execution. By taking readings at different points during program execution and calculating the difference, you can determine the CPU time consumed.
Return Value
The function returns the number of clock ticks elapsed since an epoch related to the program execution. On failure, it returns -1
.
Examples for clock()
Example 1: Measuring Execution Time of a Loop
This example demonstrates how to measure the CPU time taken by a loop performing a simple computation using clock()
.
Program
#include <stdio.h>
#include <time.h>
int main() {
clock_t start, end;
double cpu_time_used;
int i;
double sum = 0;
start = clock();
for (i = 0; i < 10000000; i++) {
sum += i;
}
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Sum: %f\n", sum);
printf("Elapsed CPU time: %f seconds\n", cpu_time_used);
return 0;
}
Explanation:
- The program records the starting clock tick using
clock()
. - A loop runs to compute the sum of numbers, simulating a time-consuming task.
- After the loop, the ending clock tick is recorded.
- The difference in clock ticks is divided by
CLOCKS_PER_SEC
to convert the result into seconds. - Both the computed sum and the elapsed CPU time are printed.
Program Output:
Sum: 49999995000000.000000
Elapsed CPU time: 0.027946 seconds
Example 2: Measuring Execution Time of a Function Call
This example shows how to measure the CPU time consumed by a specific function by invoking clock()
before and after the function call.
Program
#include <stdio.h>
#include <time.h>
void busyWork() {
volatile long i;
for (i = 0; i < 5000000; i++);
}
int main() {
clock_t start, end;
double cpu_time_used;
start = clock();
busyWork();
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Busy work execution time: %f seconds\n", cpu_time_used);
return 0;
}
Explanation:
- A helper function
busyWork()
performs a loop to simulate workload. - The
clock()
function is called before and after the invocation ofbusyWork()
to capture the start and end times. - The difference in clock ticks is calculated and converted to seconds using
CLOCKS_PER_SEC
. - The execution time of the
busyWork()
function is then printed.
Program Output:
Busy work execution time: 0.008818 seconds