Consider three C loops: one increments a volatile counter, one writes each counter value to a volatile object, and one performs an opaque addition. Timing them can reveal differences in execution cost—but first ask whether the compiler generated the operations you intended to compare. section 16.4
Choose an algorithm before coding and support its complexity assessment with proof rather than speculation. For code that runs, measure repeatedly. A timing call takes time itself and may change register handling, optimization opportunities, scheduling, or cache state. Instrumentation is part of the experiment, not a neutral observer. section 16.4
Collect elapsed times across runs, then compare means alongside variability. Inspect generated assembler when a result is surprising: the volatile-counter and volatile-store loops need not have similar instruction sequences, and GCC and Clang can compile the same loop differently. TAKEAWAY: Treat a measured difference as evidence about the compiled experiment, not automatically as a portable property of the C source. 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 table separates per-iteration time from the size of each difference and whether that difference is conclusive; not every apparent gain warrants a conclusion. section 16.4
