Sub topic 12
Warmup, Measurement and Forks
This chapter assumes you can build a JMH project with the Maven archetype, write a @Benchmark method, and use @State and @Param. It also assumes you know that the JVM compiles hot code at runtime. Here you will learn what the three timing settings do, how to configure them, and which mistakes make the numbers unreliable.
Why three settings exist
A JMH run has three layers that map to three problems with timing Java code.
- Warmup iterations run the benchmark before any timing is recorded. They give the JIT compiler time to profile and compile the hot code, so the measured phase sees steady-state code.
- Measurement iterations run after warmup. JMH records a result for each one and reports statistics across them.
- Forks start a fresh JVM for each benchmark. A fork keeps one benchmark's JIT decisions from affecting another's.
Each iteration is a time-boxed batch. JMH calls your method repeatedly for the configured duration (one second by default), counts the invocations, and turns that into a score for that iteration.
Warmup iterations
When a JVM starts, it interprets bytecode. It then compiles frequently executed methods with the C1 compiler and, after more profiling, with the optimizing C2 compiler. Early iterations therefore run slower than later ones, and the speed can change while compilation happens in the background.
Warmup iterations let this settle. JMH runs them exactly like measurement iterations, but it discards their results from the final score. You see their output in the console, which is useful for diagnosis.
You set warmup with @Warmup:
@Warmup(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)iterationsis the number of warmup iterations.timeandtimeUnitset how long each iteration lasts.
If you don't set @Warmup, JMH uses its defaults: 5 iterations of 10 seconds each in current versions. Check the version you use, because older releases used different defaults.
How much warmup is enough
There is no universal number. Look at the printed warmup scores in a real run. If scores are still dropping or jumping in the last warmup iterations, the code has not reached steady state, and you need more warmup or longer iterations.
Here is typical output where warmup is adequate:
# Warmup Iteration 1: 412.331 ns/op
# Warmup Iteration 2: 98.114 ns/op
# Warmup Iteration 3: 97.902 ns/op
Iteration 1: 97.870 ns/op
Iteration 2: 98.011 ns/opThe first warmup iteration is far slower. By the third, the score matches the measured iterations. If the measured iterations still showed a downward trend, you would add warmup.
Measurement iterations
Measurement iterations produce the numbers you report. You configure them with @Measurement, which has the same parameters as @Warmup:
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)More iterations give JMH more samples, so the reported error becomes more trustworthy. Longer iterations average out short noise such as a garbage collection pause. For a stable benchmark, five to ten iterations of one to two seconds is often enough. For noisy benchmarks, raise the count before you raise the duration, because more independent samples show you the variance.
Forks
A fork is a separate JVM process that JMH starts to run one benchmark. This matters because the JIT compiler learns from what it sees. Suppose a benchmark in the same JVM first calls an interface method with one implementation. The JIT inlines that call. A later benchmark then uses a second implementation, and the JIT must undo its assumption. The second benchmark's numbers now depend on what ran before it.
Forking avoids this profile pollution. Each benchmark starts with a clean JVM and builds its own profile.
You set forks with @Fork:
@Fork(value = 3, warmups = 0)valueis the number of forks. The default is 5 in current versions.warmupsis the number of extra forks run first and discarded. It is rarely needed.
Multiple forks also expose run-to-run variation. A JVM can settle into a different compiled shape from one start to the next, due to timing of compilation threads, memory layout, or profile differences. A single fork can hide this and give a tight but misleading error. Several forks reveal it as a wider error.
The cost is run time. Total time per benchmark is roughly:
forks × (warmup iterations × warmup time + measurement iterations × measurement time)
For the SumBenchmark class from earlier, with two @Param values, 2 forks, 3 warmup iterations and 5 measurement iterations of one second each, one method takes about 2 × 8 = 16 seconds per parameter value. That is 32 seconds in total.
Putting the settings together
This benchmark sets all three on the class. Annotations on a method override the class-level ones for that method.
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 10, time = 1)
@Fork(3)
public class TunedBenchmark {
private int[] data;
@Setup
public void setUp() {
data = new int[1000];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
}
@Benchmark
public long sum() {
long total = 0;
for (int value : data) {
total += value;
}
return total;
}
@Benchmark
@Measurement(iterations = 20, time = 2)
public long sumLongRun() {
long total = 0;
for (int value : data) {
total += value;
}
return total;
}
}Here sum uses the class settings. sumLongRun keeps the class warmup and fork settings but runs 20 measurement iterations of two seconds.
Overriding from the command line
Command-line flags override annotations, which is handy for quick experiments without editing code.
| Flag | Meaning |
|---|---|
| `-wi N` | Warmup iterations |
| `-w T` | Warmup time per iteration, for example `2s` |
| `-i N` | Measurement iterations |
| `-r T` | Measurement time per iteration |
| `-f N` | Forks |
A quick smoke run to check that a benchmark works:
java -jar target/benchmarks.jar TunedBenchmark -wi 1 -i 1 -f 1A full run for numbers you intend to keep:
java -jar target/benchmarks.jar TunedBenchmark -wi 5 -i 10 -f 3The same options work programmatically through OptionsBuilder, with .warmupIterations(5), .measurementIterations(10) and .forks(3).
Common mistakes
- Too little warmup. Early iterations include interpreted and partly compiled code. The score reflects the JVM's startup, not the code you meant to measure.
- One fork only. The error looks small, but you have sampled a single JVM's compilation outcome. Use at least 2 or 3 forks for results you rely on.
- Reading the forks as independent in the error. JMH merges all measurement iterations across forks. The reported error covers that merged set, so differences between forks widen it. A large error often means forks disagree, not that single iterations are noisy. The per-fork output shows which.
- Judging from the wrong place. Compare benchmarks only if they ran with the same settings, on the same machine, under the same load.
- Warmup that is too short for large work per call. If one call takes milliseconds, a one-second iteration holds only a few hundred invocations. Compilation triggered by invocation counts and loop back-edges may not finish. Lengthen the warmup time.
- Noisy machine. Other processes, power saving and thermal throttling shift results between forks. Close heavy applications, and rerun when numbers look odd.
Exercise
A benchmark prints warmup scores of 500, 210, 120, 118 and 117 ns/op, then measurement scores of 117, 118, 117, 118 and 117 ns/op. A second benchmark has warmup scores of 500, 300, 250, 210 and 190 ns/op, then measurement scores of 180, 170, 165, 160 and 155 ns/op. Which one has enough warmup, and what would you change for the other? Also, why would you keep 3 forks instead of 1 for both?
Show answer
The first benchmark has enough warmup. Its scores flatten after the third warmup iteration and stay stable during measurement. The second is still improving during measurement, so it has not reached steady state. Add warmup iterations or lengthen each one until the scores stop falling. Keeping 3 forks for both lets JMH start fresh JVMs, avoid profile pollution from other benchmarks, and show variation between JVM runs that a single fork could hide.
Exercise
A benchmark is configured with @Warmup(iterations = 4, time = 2), @Measurement(iterations = 6, time = 3) and @Fork(2). Roughly how long does it take for one method with no @Param?
Show answer
Each fork takes 4 × 2 + 6 × 3 = 8 + 18 = 26 seconds. Two forks take about 52 seconds, plus a small JVM startup cost per fork.