How to Measure Execution Time in C: Simple Guide
To measure execution time in C, use the
clock() function from time.h. Record the start and end times, then calculate the difference divided by CLOCKS_PER_SEC to get the time in seconds.Syntax
The clock() function returns the processor time consumed by the program since it started. You use it by calling clock() before and after the code you want to measure.
clock_t start = clock();— records the start time.clock_t end = clock();— records the end time.double time_spent = (double)(end - start) / CLOCKS_PER_SEC;— calculates elapsed time in seconds.
c
clock_t start = clock();
// code to measure
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;Example
This example measures how long it takes to run a simple loop that counts to 1 million.
c
#include <stdio.h> #include <time.h> int main() { clock_t start, end; double time_spent; start = clock(); // Code to measure long long sum = 0; for (long long i = 0; i < 1000000; i++) { sum += i; } end = clock(); time_spent = (double)(end - start) / CLOCKS_PER_SEC; printf("Sum: %lld\n", sum); printf("Execution time: %f seconds\n", time_spent); return 0; }
Output
Sum: 499999500000
Execution time: 0.005000 seconds
Common Pitfalls
Common mistakes when measuring execution time in C include:
- Not including
time.hheader, soclock()is undefined. - Using
time()instead ofclock()for fine-grained timing;time()measures wall-clock time in seconds and is less precise. - Dividing by
CLOCKS_PER_SECincorrectly or forgetting to cast todouble, causing integer division and wrong results. - Measuring very fast code without enough workload, resulting in zero or near-zero time.
c
/* Wrong way: integer division causes zero time */ clock_t start = clock(); // fast code clock_t end = clock(); int time_spent = (end - start) / CLOCKS_PER_SEC; // wrong: int and integer division /* Right way: use double and cast */ double time_spent_correct = (double)(end - start) / CLOCKS_PER_SEC;
Quick Reference
| Step | Code | Description |
|---|---|---|
| 1 | Include | Access clock() and CLOCKS_PER_SEC |
| 2 | clock_t start = clock(); | Record start time |
| 3 | // code to measure | Place code you want to time here |
| 4 | clock_t end = clock(); | Record end time |
| 5 | double time_spent = (double)(end - start) / CLOCKS_PER_SEC; | Calculate elapsed time in seconds |
| 6 | printf("%f", time_spent); | Display the time taken |
Key Takeaways
Use clock() from time.h to measure CPU time in C programs.
Calculate elapsed time by subtracting start from end and dividing by CLOCKS_PER_SEC.
Cast to double before division to avoid integer division errors.
Measure enough workload to get meaningful timing results.
Avoid using time() for fine-grained execution time measurement.