Measuring elapsed time in C
clock counts processor time; use CLOCKS_PER_SEC to make it meaningful.
#include <stdio.h>
#include <time.h>
double time_work(long iterations) {
clock_t started = clock();
volatile long sink = 0;
for (long i = 0; i < iterations; i++) {
sink += i % 7;
}
clock_t finished = clock();
return (double) (finished - started) / CLOCKS_PER_SEC;
}
void benchmark(void) {
printf("%.4f seconds\n", time_work(5000000L));
}
How it works
clock()returns processor time, not wall-clock time.- Dividing by
CLOCKS_PER_SECgives seconds. - For wall-clock,
timeor a POSIX clock is the right call.
Keywords and builtins used here
benchmarkclock_tdoubleforlongreturntime_workvoidvolatile
The run, in numbers
- Lines
- 18
- Characters to type
- 341
- Tokens
- 90
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 54 seconds.
Step 2 of 2 in Time, step 6 of 14 in Systems programming.