Sub topic 2
Benchmark Modes and Time Units
Assume you know basic Java, annotations, Maven, and that the JVM compiles frequently used code at runtime. This chapter focuses on writing reliable JMH benchmark methods.
Benchmark modes and time units
A benchmark mode defines what JMH measures.
| Mode | Meaning | Typical use |
|---|---|---|
| `Throughput` | Operations per unit of time | Requests or tasks per second |
| `AverageTime` | Time per operation | Latency of one operation |
| `SampleTime` | Distribution of operation times | Finding latency outliers |
| `SingleShotTime` | Time for one operation | Startup or one-time work |
@OutputTimeUnit chooses the unit shown in the result. It does not change the measured work.
Sharing data with `@State`
A @State object holds data that benchmark methods use. JMH creates and manages these objects according to their scope:
Scope.Threadgives each benchmark thread its own object.Scope.Benchmarkshares one object across threads.Scope.Groupshares one object among threads in the same group.
Use Scope.Thread unless sharing is part of what you want to measure.
Preparing data with `@Setup` and `@TearDown`
@Setup runs before a benchmark, so data preparation is not accidentally included in the measured operation. @TearDown runs afterward for cleanup. Their level controls when they run:
Level.Trial: once for the complete benchmark configuration.Level.Iteration: before or after each warmup or measurement iteration.Level.Invocation: before or after each benchmark invocation.
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class SumBenchmark {
@Param({"10", "1000"})
public int size;
private int[] values;
@Setup(Level.Trial)
public void setUp() {
values = new int[size];
for (int i = 0; i < size; i++) {
values[i] = i;
}
}
@TearDown(Level.Trial)
public void tearDown() {
values = null;
}
@Benchmark
public long sum() {
long result = 0;
for (int value : values) {
result += value;
}
return result;
}
@Benchmark
public void consumeSum(Blackhole blackhole) {
blackhole.consume(sum());
}
}@Param makes JMH run the benchmark once for each listed value. This exposes how input size affects performance.
Dead-code elimination and `Blackhole`
The JIT compiler may remove work whose result is never used. Returning a result from a benchmark method tells JMH to consume it. Blackhole is useful when a method produces several values or has a void return type.
Exercise
Which mode should you choose to measure the average latency of one operation, and how can you prevent its result from being discarded?
Show answer
Use Mode.AverageTime and return the result, or pass it to a Blackhole.