Performance Analysis
Timing a small loop like the one above gave nearly zero time even for large N. What is the most likely cause?
start = now();
for (i = 0; i < N; i++)
x = a * b + i;
end = now();
- AThe CPU has a special instruction that finishes the computation instantly
- BBecause x is never used afterward, the compiler removed the loop computation as unnecessary
- CThe clock function is broken
Show answer and explanation
Answer: B. Because x is never used afterward, the compiler removed the loop computation as unnecessary
With optimization enabled, compilers remove computations whose results are unused as dead code, or compute loop results ahead of time and replace them with constants. So in microbenchmarks that isolate a small piece of code, the computation being measured may not actually run. Countermeasures include printing the result, using volatile or other means of defeating the optimization, and inspecting the generated machine code.
- A. No such instruction exists.
- B. Correct. It is a common microbenchmark pitfall.
- C. The clock works correctly.