To time a C loop, call timespec_get before and after it. Those calls are instrumentation: they observe execution, but they also become part of the program being measured. A call can require register saves, limit compiler optimizations, and affect scheduling or caches. section 16.4
Listing 16.7 Instrumenting three for loops with struct timespec
timespec_get(&t[0], TIME_UTC);
/* Volatile for i ensures that the loop is effected */
for (uint64_t volatile i = 0; i < iterations; ++i) {
/* do nothing */
}
timespec_get(&t[1], TIME_UTC);
/* s must be volatile to ensure that the loop is effected */
for (uint64_t i = 0; i < iterations; ++i) {
s = i;
}
timespec_get(&t[2], TIME_UTC);
/* Opaque computation ensures that the loop is effected */
for (uint64_t i = 1; accu0 < upper; i += 2) {
accu0 += i;
}
timespec_get(&t[3], TIME_UTC);
Three loops bracketed by timespec_get show how the measured work—and the use of volatile to keep work from being optimized away—can differ. section 16.4
TAKEAWAY: Instrumentation changes compile-time and run-time properties. Assess its cost before interpreting a timing result. Repeat measurements and report their mean and variation; a small apparent difference may be inconclusive. section 16.4
Table 16.1 Comparison of measurements
| Loop | Sec per iteration | Difference | Gain/loss | Conclusive | |
|---|---|---|---|---|---|
| 0 | volatile loop |
1.97⋅10-09 | |||
| 1 | volatile store |
3.66⋅10-10 | -1.60⋅10-09 | -81% | Yes |
| 2 | Opaque addition | 3.45⋅10-10 | -2.10⋅10-11 | -6% | No |
| 3 | Plus timespec_get |
1.77⋅10-08 | 1.74⋅10-08 | +5043% | Yes |
| 4 | Plus mean | 2.62⋅10-08 | 8.5⋅10-09 | +48% | Yes |
| 5 | Plus variance | 2.90⋅10-08 | 2.8⋅10-09 | +11% | Yes |
| 6 | Plus skew | 3.17⋅10-08 | 2.7⋅10-09 | +9% | Yes |
The comparison separates loop costs from the added costs of clock calls and collecting mean, variance, and skew. section 16.4












