C time clock() Function
Example
Measure how long a loop takes:
clock_t start = clock();
long long sum = 0;
for (int i = 0; i < 10000000; i++) {
sum += i;
}
clock_t end = clock();
double seconds = (double)(end - start) / CLOCKS_PER_SEC;
printf("Sum: %lld\n", sum);
printf("Time: %f seconds\n", seconds);
Definition and Usage
The clock() function returns how much processor time the program has used, in clock ticks (small units of time).
To get the time in seconds, divide the result by CLOCKS_PER_SEC. Convert to double first, or the result can lose its decimals.
clock() is often used to measure how long a piece of code takes. The time is a little different each time you run the program.
Note: clock() measures processor time, not real time. If the program waits, for example for user input, the waiting time is not counted. To measure real time, use time() and difftime().
The clock() function is defined in the <time.h> header file.
Syntax
clock_t clock(void);
Technical Details
| Returns: | A clock_t value with the number of clock ticks that the program has used, or (clock_t)(-1) if the time is not available. |
|---|
Related Pages
Read more about dates and times in our C Date and Time Tutorial.