Sub topic 5
Your first @Benchmark method
This chapter assumes you can read basic Java and annotations. It also assumes you have a JMH project built from the Maven archetype (see the previous chapter), so that mvn clean verify produces target/benchmarks.jar.
What a benchmark method is
A benchmark method is a public method annotated with @Benchmark. JMH does not call it once. During the warmup and measurement phases, it calls the method in a loop that it generates and controls. You write only the work to measure. JMH supplies the timing, the iteration count and the repetition.
The annotation processor runs at build time. It reads your annotated classes and generates extra source code, including the measurement loops. This is why you must run the build through Maven and launch the generated jar. Running your class's main method directly does not work.
A minimal example
The class below measures summing an int array. The array is built once, in a field of the benchmark class.
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.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;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class FirstBenchmark {
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;
}
}Three parts matter here:
@Benchmarkmarkssum()as the code to measure. Only this body is timed.@State(Scope.Benchmark)tells JMH to create one instance of the class and share it. Later chapters cover scopes in detail.@Setupruns before measurement, so building the array is not part of the score.
Class-level @BenchmarkMode and @OutputTimeUnit set how the result is reported. The "Benchmark modes and time units" chapter explains them.
Return the result
The method returns total. JMH consumes every returned value. If sum() were void and computed total without using it, the JIT compiler could decide the loop has no visible effect and remove it. The benchmark would then report a very small time for work that never ran. Returning the value is the simplest defense. The next chapter covers this and Blackhole.
Build and run
mvn clean verify
java -jar target/benchmarks.jar FirstBenchmarkThe argument is a regular expression matched against benchmark names. Without it, JMH runs every benchmark in the jar. You will see warmup and measurement iterations printed for each fork, then a summary table.
Common mistakes
- Declaring the method
privateorstaticwith a state field. The method must be public, and it works best as an instance method. - Putting setup work inside the benchmark method. Data construction then counts toward the score.
- Running the class from the IDE
mainmethod without the Runner API. The generated code is missing, so nothing runs. - Editing the class and running the old jar. Rebuild with
mvn clean verifyafter every change.
Exercise
In FirstBenchmark, sum() is changed to return void, and the loop result is stored in a local variable that is never read. Why might the reported time drop sharply, and what is the smallest change that fixes it?
Show answer
The JIT compiler can see that the local variable is never used and remove the loop as dead code, so the benchmark measures an empty method. The smallest fix is to return the computed value from the method, as in public long sum(), so JMH consumes it.