Sub topic 9
Comparing input sizes with @Param
This chapter assumes you can write a @Benchmark method, that you know what a @State class is, and that you know how @Setup(Level.Trial) prepares data. It builds on the previous chapters and adds one idea: running the same benchmark across several inputs.
Why one input size is not enough
A benchmark at a single input size gives you one point on a curve. Many things change with size:
- An algorithm with O(n) cost and one with O(n log n) cost look alike at n = 100 and differ clearly at n = 1,000,000.
- Small data fits in the CPU cache. Large data does not, so the cost per element can jump.
- Constant overhead, such as a method call or a small allocation, dominates at small sizes and disappears at large ones.
You could copy the benchmark class once per size. That is tedious, and the copies drift apart. JMH solves this with @Param, which runs one benchmark class once for each value you list.
How @Param works
@Param goes on a field of a @State class. You give it an array of strings. JMH sets the field to each value in turn and runs the full benchmark for that value.
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.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
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 = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class SizeBenchmark {
@Param({"100", "10000", "1000000"})
public int size;
private int[] data;
@Setup(Level.Trial)
public void setUp() {
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = i;
}
}
@Benchmark
public long sum() {
long total = 0;
for (int value : data) {
totalreturn total;
}
}Four rules explain how this behaves.
- MH converts each string to the field's type. This works for primitives, their wrappers,
String, and enums (matant name). A value that cannot be converted, such as"abc"for anint, fails when the benchmThe field must be public and non-final. JMH assigns it by reflection-likefinalfield cannot be set. - Data is built in
@Setup, not in a field initializer. JMH sets the parameter constructs the state object. A field initializer such asint[] data = new int[size];would seesizeas 0. Use@Setup(Level.Trial)so the data is built once per trial, after the parameters are in place. - The benchmark runs once per value. Each value gets its own warmup, measurement, and forks. Results for different sizes never share a JVM.
Several parameters multiply
With two or more @Param fields, JMH runs every combination (the Cartesian product). The next class compares two list implementations at two sizes.
package org.sample;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
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.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
@Fork(1)
public class ListSumBenchmark {
@Param({"ArrayList", "LinkedList"})
public String type;
@Param({"1000", "100000"})
public int size;
private List<Integer> list;
@Setup(Level.Trial)
public void setUp() {
list = type.equals("ArrayList") ? new ArrayList<>() : new LinkedList<>();
for (int i = 0; i < size; i++) {
list.add(i);
}
}
@Benchmark
public long sum() {
long total = 0;
for (int value : list) {
total += value;
}
return total;
}
}This produces four runs: ArrayList/1000, ArrayList/100000, LinkedList/1000, and LinkedList/100000. The order in which JMH lists them is not something to rely on. Read the parameter columns in the output instead.
Running time grows with every parameter
The total run time is roughly:
combinations × forks × (warmup iterations + measurement iterations) × iteration timeFor SizeBenchmark this is 3 sizes × 2 forks × (3 + 5) iterations × 1 s = 48 seconds, plus JVM startup. Adding a second parameter with three values would triple that. Keep the value lists short, and choose values that are far apart (for example 100, 10,000, 1,000,000) so that differences in behavior are visible.
Overriding values without editing code
The annotation values are defaults. You can replace them at run time with the -p option. This is useful for trying one size quickly or for trying a size you did not plan for.
java -jar target/benchmarks.jar SizeBenchmark -p size=1000,50000
java -jar target/benchmarks.jar ListSumBenchmark -p type=ArrayList -p size=1000Separate several values for one parameter with commas. Repeat -p to set different parameters. A -p value replaces the annotation's whole list for that parameter.
You can do the same from code with the Runner API:
package org.sample;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class ParamRunner {
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(ListSumBenchmark.class.getSimpleName())
.param("type", "ArrayList", "LinkedList")
.param("size", "1000")
.forks(1)
.build();
new Runner(options).run();
}
}Reading parameterized results
JMH adds one column per parameter, in parentheses. The following output is illustrative. Your numbers depend on your hardware.
Benchmark (size) Mode Cnt Score Error Units
SizeBenchmark.sum 100 avgt 10 28.4 ± 0.6 ns/op
SizeBenchmark.sum 10000 avgt 10 2950.1 ± 41.3 ns/op
SizeBenchmark.sum 1000000 avgt 10 310200.7 ± 5120.9 ns/opCompare rows with the same benchmark and different parameters by looking at how the score scales:
- The size grew 100 times (100 to 10,000) and the score grew about 104 times. That is close to linear, as expected for a sum.
- From 10,000 to 1,000,000 the size grew 100 times and the score grew about 105 times. If the ratio were much larger than the size ratio, you would suspect a cache or memory effect.
Dividing the score by the size gives cost per element. Here it is about 0.28, 0.30, and 0.31 ns. A flat cost per element means the work scales linearly. A rising cost per element points to memory effects. Check the error column too. If the error is large relative to the difference between two rows, the difference is not reliable. Compare only rows that use the same units.
Common mistakes
- Initializing in the field or constructor. The parameter is still at its default value then. Use
@Setup. - Using
Level.Invocationto rebuild large data per size. The setup cost then runs before every call and can distort timings for small benchmarks. PreferLevel.Trialunless each call mutates the data. - Letting memory run out at large sizes. A size of 100,000,000
intvalues is 400 MB. Raise the heap with@Fork(jvmArgsAppend = "-Xmx2g")if needed. - Hiding the work for some sizes. At a tiny size the JIT may optimize the loop differently. Keep returning the result, as covered in the dead-code chapter, so every size does real work.
- Comparing across benchmarks that use different data. If two benchmark classes build their data differently, a difference in score may come from the data and not the code under test.
Exercise
A benchmark class has @Param({"10", "100", "1000"}) on one field and @Param({"A", "B"}) on another. It uses @Fork(2), @Warmup(iterations = 2, time = 1), and @Measurement(iterations = 3, time = 1). Roughly how many seconds of iteration time will a full run take, ignoring JVM startup, and why must the data array be built in @Setup and not in a field initializer?
Show answer
There are 3 × 2 = 6 combinations. Each runs in 2 forks, and each fork has 2 + 3 = 5 one-second iterations. That is 6 × 2 × 5 = 60 seconds. The data must be built in @Setup because JMH sets the @Param field after it constructs the state object, so a field initializer would read the parameter before it has its real value.