Sub topic 1
Why hand-written timing loops mislead
Prerequisites
This chapter assumes you can read basic Java classes and methods. You should know how to run a Java program from the command line. You should also know that the JVM compiles frequently used code while the program runs. Maven and JMH annotations are not needed yet. They appear in later chapters.
The tempting approach
The first idea most developers have for measuring a piece of code is to wrap it in System.nanoTime() calls:
public class NaiveTiming {
static int[] data = new int[10_000];
static long sum() {
long total = 0;
for (int value : data) {
total += value;
}
return total;
}
public static void main(String[] args) {
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
long start = System.nanoTime();
sum();
long elapsed = System.nanoTime() - start;
System.out.println("sum took " + elapsed + " ns");
}
}This program compiles and runs. The number it prints is close to meaningless. Run it five times and you will probably see five very different values. The rest of the chapter explains why.
Why a single timing is unreliable
A single call measured this way suffers from several separate problems.
- Timer resolution and overhead.
System.nanoTime()has a cost of its own, often tens of nanoseconds. If the code you measure takes about as long as the timer call, the timer dominates the result. - Cold code. The first call runs in the interpreter, not as optimized machine code. You measure the slowest version of your code.
- Class loading and initialization. The first use of a class can trigger loading, linking, and static initialization. That work lands inside your measured interval.
- Noise from the machine. Other processes, the operating system scheduler, CPU frequency changes, and garbage collection all add time that has nothing to do with your code.
The usual response is to repeat the work in a loop and divide by the iteration count. That helps with timer overhead and noise. It does not fix the problems that come from the JVM itself.
Warmup and JIT compilation
The JVM does not run your bytecode at one fixed speed. It starts by interpreting bytecode. It counts how often each method and loop runs. When a method becomes hot, the just-in-time (JIT) compiler turns it into machine code. HotSpot uses tiered compilation. Code moves through several levels:
- The interpreter runs the bytecode and collects counts.
- The C1 compiler produces quickly compiled code with light optimization.
- The C2 compiler produces heavily optimized code, using the profile data gathered earlier.
Because compilation happens on background threads while your code keeps running, performance changes during the run. The early iterations are slow. Later ones are fast. The point where speed settles is called steady state. Warmup is the period before steady state.
The arrow back to the interpreter matters. C2 makes optimistic assumptions based on the profile, for example that a branch is never taken or that a call has only one target class. If an assumption later proves false, the JVM discards the compiled code and falls back. This is called deoptimization. A benchmark can therefore speed up and then slow down again.
Seeing warmup in practice
You can observe warmup by timing the same call many times and printing each result:
public class WarmupDemo {
static int[] data = new int[10_000];
static long sum() {
long total = 0;
for (int value : data) {
total += value;
}
return total;
}
public static void main(String[] args) {
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
long sink = 0;
for (int round = 0; round < 15; round++) {
long start = System.nanoTime();
for (int i = 0; i < 1_000; i++) {
sink += sum();
}
long elapsed = System.nanoTime() - start;
System.out.println("round " + round + ": " + elapsed / 1_000 + " ns per call");
}
System.out.println("sink = " + sink);
}
}On a typical machine the first rounds are several times slower than the later ones. The exact numbers depend on your hardware and JDK, so run it yourself. The shape is what matters: a high start, a drop, and then a plateau.
Notice that the program prints sink at the end. That is deliberate and it leads to the next problem.
The compiler can delete your code
The JIT compiler removes work whose result is never used. This is called dead-code elimination. Consider this loop:
public class DeadCodeDemo {
static double compute(double x) {
return Math.sqrt(x) * Math.sin(x);
}
public static void main(String[] args) {
long start = System.nanoTime();
for (int i = 0; i < 100_000_000; i++) {
compute(i);
}
long elapsed = System.nanoTime() - start;
System.out.println("per call: " + (double) elapsed / 100_000_000 + " ns");
}
}The return value of compute is thrown away. Once the loop is compiled, the JIT can prove that the calls have no visible effect and remove them. The reported time can drop to nearly nothing. You would conclude the method is almost free, when in fact the benchmark measured an empty loop.
A related effect is constant folding. If the input is a constant, such as Math.sqrt(2.0), the compiler can compute the answer once at compile time. The benchmark then measures reading a constant. Later chapters cover both effects in detail and show how JMH prevents them.
Other ways loops mislead
Dead-code elimination and constant folding are not the only distortions. Several more are common in hand-written loops.
- Loop optimizations. The compiler may unroll the loop, hoist invariant work out of it, or vectorize it. Your loop may be faster or slower than the same operation in real code.
- On-stack replacement (OSR). If your loop is in
mainand runs long, the JVM compiles it while it is already executing and swaps in the new code mid-loop. OSR-compiled code is often less optimized than a normally compiled method. Putting the loop inmaincan therefore give different results from calling a method repeatedly. - Profile pollution. The JVM records which types and branches it sees. If one loop measures several implementations in turn, the profile from the first one affects the optimization of the next. The order of your measurements changes the answer.
- Garbage collection. A loop that allocates objects triggers collections at unpredictable times. One run may include a pause and another may not.
- Shared state between runs. Code measured later in the same JVM inherits already compiled code, a warmed heap, and a populated profile from code measured earlier.
Why you cannot simply fix it by hand
It is possible to reduce each problem manually. You could add a warmup loop, consume results into a field, run in separate JVM processes, and repeat measurements to estimate variance. Doing all of it correctly is difficult and easy to get subtly wrong. Each fix also has its own pitfalls. For example, a warmup that is too short leaves you measuring mixed-mode code, and a warmup that exercises different types than the measured phase leaves a misleading profile.
The practical requirements for a trustworthy measurement are therefore:
| Problem | What a reliable harness must do |
|---|---|
| Cold code and compilation | Run warmup iterations and discard them |
| Timer overhead | Measure many invocations per timed interval |
| Dead-code elimination | Consume every result |
| Constant folding | Read inputs from fields the compiler cannot treat as constants |
| Profile pollution and shared state | Run each benchmark in a fresh JVM |
| Noise and variance | Repeat measurements and report an error estimate |
JMH, the Java Microbenchmark Harness, is built to cover exactly this list. It is maintained by the OpenJDK project and is the tool the JDK developers use for their own performance work. The following chapters show how each row of the table maps to a JMH feature.
What a benchmark can and cannot tell you
Even a correct microbenchmark answers a narrow question: how fast does this small piece of code run under these conditions? It does not tell you how the whole application behaves, where cache sizes, contention, and real data distributions matter. Treat microbenchmark results as evidence for a specific comparison, and confirm important decisions with measurements closer to production.
Exercise
A developer wraps a loop of 100 million calls to compute(i) in System.nanoTime() calls and discards the return value of compute. The result is 0.3 ns per call. Name the most likely cause and one other effect that could distort a loop like this.
Show answer
The most likely cause is dead-code elimination. The JIT compiler sees that the results are never used and removes the calls, so the loop measures almost nothing. Other valid effects are constant folding, warmup and on-stack replacement when the loop sits in main, profile pollution from earlier measurements, and garbage collection pauses.
Exercise
Why does measuring the same method in the same JVM, first with one implementation and then with another, produce results that depend on the order of measurement?
Show answer
The JVM builds a profile of the types and branches it sees and compiles code based on it. The first implementation shapes that profile and the compiled code, so the second implementation is optimized under different assumptions (profile pollution). Already compiled code and a warmed heap also carry over. Running each benchmark in a fresh JVM avoids this.