Measuring execution time with clock()
What you'll learn: How to use the standard library to calculate exactly how many seconds your code takes to run.
The Stopwatch Approach
Imagine you are timing a sprinter. You click a stopwatch the moment they leave the blocks and click it again as they cross the finish line. The difference between those two times is their performance score. In C, we do the exact same thing using the clock() function from the <time.h> header.
The clock() function returns the number of "clock ticks" elapsed since the program started. However, because different computers process ticks at different speeds, we divide that number by a constant called CLOCKS_PER_SEC to convert those abstract ticks into human-readable seconds.
Implementing the Timer
To measure a specific block of code, you need to capture the start time, run your code, capture the end time, and then perform a simple subtraction. Since the result of the division is often a fraction (like 0.002 seconds), we usually cast the result to a double.
#include <stdio.h>
#include <time.h>
int main() {
// 1. Capture the start time
clock_t start = clock();
// 2. Perform the work (e.g., a long loop)
double sum = 0;
for (int i = 0; i < 100000000; i++) {
sum += i;
}
// 3. Capture the end time
clock_t end = clock();
// 4. Calculate the difference in seconds
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("Result: %f\n", sum);
printf("Execution time: %f seconds\n", time_spent);
return 0;
}
Why this matters
When you are optimizing a program, your intuition can be wrong. You might think one version of a function is faster than another, but "feeling" fast isn't a metric. By wrapping your algorithms in clock() calls, you get hard data.
One thing to keep in mind: clock() measures CPU time. If your program pauses to wait for a user to type something, that idle time isn't always counted the same way across all operating systems. It is best used for measuring "heavy lifting" tasks like sorting large arrays or complex math.
Key takeaway
Use (double)(end - start) / CLOCKS_PER_SEC to turn processor ticks into measurable seconds for performance testing.