Sub topic 5
Your first @Benchmark method
This chapter assumes you can write basic Java classes, you know what annotations are, and you can run Maven from the command line. It also assumes you know that the JVM compiles hot code at runtime. You will write one benchmark class, build it, run it, and learn what each part of it does.
What a @Benchmark method is
A benchmark method is a public method annotated with @Benchmark. JMH finds these methods at build time. An annotation processor generates extra classes that call your method in a timed loop. You never write the loop yourself.
The method body is the code you want to measure. Everything else, such as input data and settings, lives outside the method body. This keeps the measured region small and focused.
JMH has a few rules for benchmark methods:
- The method must be
public. - The enclosing class must be
publicand must not be final. - The method can return a value or return
void. - The method can take parameters, but only state objects and
Blackhole. You will meet both later. - If the method declares checked exceptions, JMH handles them. You do not need a try/catch.
Generate the project
The JMH Maven archetype creates a project that builds a self-contained jar. That jar holds your benchmarks, JMH itself, and the generated code.
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample \
-DartifactId=benchmarks \
-Dversion=1.0
cd benchmarks
mvn clean verify
java -jar target/benchmarks.jarThe archetype puts a sample class in src/main/java/org/sample/MyBenchmark.java. You can delete it or replace it with the class below. Running java -jar target/benchmarks.jar with no arguments runs every benchmark in the project, so remove classes you do not want to run.
A complete benchmark class
This class sums an array of integers. It uses a few annotations that are covered in detail in later chapters. This chapter explains only what you need to read the code.
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 SumBenchmark {
@Param({"100", "10000"})
public int size;
private int[] data;
@Setup(public void setUp() {
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = i;
}
}
@Benchm {
long total = 0;
for (int value : data) {
total += value;
}
return total;
}
}What part does
| Part | Role |
|---|---|
| `@Benchmark` on `sum()` | method JMH will time. |
| `@State(Scope.Benchmark)` | Mak own state object, shared by all threads. |
| `@Param({"100", "10000"})` | Runole benchmark once for each listed value of `size`. |
| `@Setup(Level.Trial)` | Builds the array once perside the timed region. |
| `@BenchmarkMode`, `@OutputTimeUnit` | Choose what is measured and how the score is displayed. |
| `@Warmup`, `@Measurement`, `@Fork` | Control how many warmup rounds, measured rounds, and JVM processes are used. |
The array is built in setUp(), not inside sum(). If you built it inside the benchmark method, you would measure array allocation and filling together with the summing. Keep setup work out of the method body unless allocation is the thing you want to measure.
Why the method returns a value
The method returns total. This is deliberate. JMH takes every returned value and passes it to an internal Blackhole. A Blackhole is an object that consumes values in a way the JIT compiler cannot prove is useless.
Without that, the JIT could notice that total is never used and delete the whole loop. The benchmark would then report a tiny, meaningless time. This problem is called dead-code elimination, and a later chapter covers it in depth. For now, follow one rule: return the result of the computation from the benchmark method.
If you have more than one result, you can take a Blackhole parameter and call consume on each value.
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class TwoResultsBenchmark {
private double x = Math.PI;
@Benchmark
public void twoResults(Blackhole bh) {
bh.consume(Math.log(x));
bh.consume(Math.sqrt(x));
}
}The input x is a field, not a literal. If you wrote Math.log(Math.PI), the JIT could compute the answer at compile time and the benchmark would measure nothing. This is constant folding, and it also gets its own chapter.
How JMH runs your method
JMH does not call sum() once. Understanding the structure helps you read the output.
- JMH starts a fresh JVM, called a fork.
- In that JVM it runs the warmup iterations. Each iteration calls your method repeatedly for the configured time, here one second. These results are discarded.
- It then runs the measurement iterations in the same way. These results are recorded.
- The fork ends. JMH repeats the process for the next fork.
- JMH repeats everything for the next
@Paramvalue.
With the settings above, SumBenchmark runs 2 forks, each with 3 warmup and 5 measurement iterations of one second each. That is 16 seconds per fork, so about 32 seconds per @Param value. With two values, expect roughly one minute plus JVM startup time.
Running from the command line
Run the jar with a pattern that selects benchmarks by name. The pattern is a regular expression matched against the fully qualified benchmark name.
java -jar target/benchmarks.jar SumBenchmark -wi 3 -i 5 -f 1 -prof gcThe flags override the annotations. Here -wi 3 sets three warmup iterations, -i 5 sets five measurement iterations, and -f 1 sets one fork. The -prof gc flag adds the GC allocation profiler. Using one fork is faster for a first try, but two or more forks give more trustworthy results.
Running from an IDE
You can also start a benchmark from a main method with the Runner API. This is handy in an IDE, but the annotation processor must still have run, so build with Maven at least once.
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 BenchmarkRunner {
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(SumBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();
}
}Reading the first result
The output ends with a table similar to this one. Your numbers will differ.
Benchmark (size) Mode Cnt Score Error Units
SumBenchmark.sum 100 avgt 10 35.2 ± 0.8 ns/op
SumBenchmark.sum 10000 avgt 10 3120.4 ± 41.5 ns/opEach row is one @Param value. avgt means average time. Cnt is the number of measurement iterations recorded across all forks, here 2 forks times 5 iterations. Score is the mean time for one call to the method. Error is the half-width of a 99.9 percent confidence interval around that mean. The unit ns/op means nanoseconds per operation, where one operation is one call to sum().
The larger array takes about 89 times longer than the smaller one for 100 times more elements. That is a plausible result, since the small case has fixed per-call overhead.
Common mistakes
- Doing setup inside the method. Allocating inputs inside the benchmark method adds that cost to every measurement.
- Discarding the result. A
voidmethod that computes something and drops it invites dead-code elimination. - Using constants as input. Literals and
static finalvalues can be folded at compile time. Read inputs from state fields. - Running from the IDE without the processor. If you see "no benchmarks to run", the generated classes are missing. Run
mvn clean verifyfirst. - Trusting one fork. Run-to-run variation between JVM processes is real. Use at least two forks for results you plan to compare.
Exercises
Exercise
The benchmark method sum() returns total. What would likely happen if you changed its return type to void and removed the return statement, and why?
Show answer
The JIT compiler could see that total is never used, treat the loop as dead code, and remove it. The benchmark would then report a very small time that does not reflect the cost of summing the array. Returning the value makes JMH pass it to a Blackhole, which prevents this.
Exercise
A benchmark class has @Param({"10", "100", "1000"}), @Fork(3), @Warmup(iterations = 2, time = 1) and @Measurement(iterations = 4, time = 1). Roughly how many seconds of iteration time does a full run take, ignoring JVM startup?
Show answer
Each fork runs 2 warmup and 4 measurement iterations of one second, so 6 seconds. Three forks give 18 seconds per parameter value. Three parameter values give about 54 seconds.