Sub topic 6
Benchmark modes and time units
This chapter covers what a benchmark mode measures, how to choose one, and how @OutputTimeUnit changes the way results are printed. It assumes you can write a basic @Benchmark method, build the JMH jar with Maven, and run it from the command line. It also assumes you know that the JVM compiles hot code while the program runs.
What a mode decides
A benchmark method is only code to run. The mode tells JMH what to measure while that code runs. The same method can report "how long does one call take?" or "how many calls finish per second?". Both numbers describe the same code, but they answer different questions and have different units.
You set the mode with @BenchmarkMode. If you leave it out, JMH uses Mode.Throughput.
JMH has these modes:
| Mode | Reports | Typical unit | Better result |
|---|---|---|---|
| `Throughput` | Operations completed per unit of time | ops/s | Higher |
| `AverageTime` | Mean time for one operation | ns/op | Lower |
| `SampleTime` | Distribution of individual call times, with percentiles | ns/op | Lower |
| `SingleShotTime` | Time of exactly one call, with no repeated calls inside an iteration | ns/op | Lower |
| `All` | Runs every mode above | mixed | Depends on mode |
Throughput and average time are mirror images. If one operation takes 50 ns, the throughput is about 20 million ops/s. Pick the one that matches how you think about the code. Services are usually discussed in requests per second. Small utility methods are usually discussed in nanoseconds per call.
Choosing a mode
Put the annotation on the class to apply it to every benchmark in the class, or on a method to override the class setting.
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.State;
import org.openjdk.jmh.annotations.Warmup;
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
public class ModesBenchmark {
private final StringBuilder builder = new StringBuilder();
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public int throughput() {
return "hello".concat("world").length();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int averageTime() {
return "hello".concat("world").length();
}
@Benchmark
@BenchmarkMode(Mode.SampleTime)
public int sampleTime() {
return "hello".concat("world").length();
}
@Benchmark
@BenchmarkMode({Mode.Throughput, Mode.AverageTime})
public int twoModes() {
builder.setLength(0);
return builder.append("hello").append("world").length();
}
}The last method shows that @BenchmarkMode accepts an array. JMH then runs the method once per listed mode and prints one result line for each. This multiplies the run time, because each mode runs its own warmup and measurement iterations.
Each result line carries a label such as thrpt, avgt, sample or ss. Check this label before you compare numbers from two runs.
Throughput
In Throughput mode, JMH calls the method repeatedly for the length of an iteration and counts the calls. The score is calls divided by elapsed time. A score of 18 000 000 ops/s means about 18 million calls finished in each second.
Use throughput when you want a rate and when higher should mean better. It is also the natural choice for multithreaded benchmarks, where the total rate across threads matters.
Average time
In AverageTime mode, JMH divides the elapsed time by the number of calls. The score is the mean time for one call, for example 55.3 ns/op.
Use it when you compare two implementations of the same small operation. A lower number is better, and the unit reads naturally ("this call costs 55 nanoseconds").
A mean hides outliers. If one call in a thousand pauses for garbage collection, the mean moves only slightly, and you see no sign of the slow call.
Sample time
SampleTime does not time every call. JMH picks calls at intervals, times each of those, and keeps the individual timings. At the end it reports the mean and also percentiles.
The output includes lines like these:
Benchmark Mode Cnt Score Error Units
ModesBenchmark.sampleTime sample 412300 58.2 ± 0.4 ns/op
ModesBenchmark.sampleTime:sampleTime·p0.50 sample 50.0 ns/op
ModesBenchmark.sampleTime:sampleTime·p0.99 sample 120.0 ns/op
ModesBenchmark.sampleTime:sampleTime·p0.999 sample 310.0 ns/op
ModesBenchmark.sampleTime:sampleTime·p1.00 sample 41984.0 ns/opThe numbers above are an illustration of the layout, not real measurements. Read them like this: p0.50 is the median, and p0.99 means 99% of the sampled calls were at least that fast. p1.00 is the slowest sampled call.
Use SampleTime when tail latency matters, such as in a request handler where the slowest calls hurt users. Keep in mind that it times each sampled call with the clock, so the clock cost is part of the result. For very short methods, that cost can be a large share of the number.
Single shot time
SingleShotTime calls the method once per iteration and times that one call. There is no repetition inside the iteration and, by default, no warmup.
This mode measures a cold start: the first call into code that the JVM has not yet optimized. It suits questions such as "how long does the first request take after startup?" It does not suit normal steady-state comparisons, because the result describes interpreted or lightly compiled code.
Because one call is so noisy, combine this mode with many forks, so that each fork gives a fresh JVM and a fresh first call:
java -jar target/benchmarks.jar ColdStartBenchmark -bm ss -f 20 -wi 0 -i 1Here -bm selects the mode (the short names are thrpt, avgt, sample, ss and all), -f sets the forks, -wi the warmup iterations and -i the measurement iterations.
Output time units
@OutputTimeUnit sets the unit used in the printed result. It takes a java.util.concurrent.TimeUnit value.
How the unit applies depends on the mode:
- In throughput mode the unit is the denominator of the rate.
TimeUnit.SECONDSgives ops/s, andTimeUnit.MILLISECONDSgives ops/ms. - In the time modes the unit is the time per operation.
TimeUnit.NANOSECONDSgives ns/op, andTimeUnit.MICROSECONDSgives us/op.
The unit only changes how the number is displayed. It does not change what is measured. A result of 0.055 us/op and one of 55 ns/op are the same measurement.
Choose a unit that gives readable numbers, roughly between 1 and 10 000. A score of 0.000055 s/op is hard to compare. Use the same unit for every benchmark you want to compare, because it is easy to misread 1.2 us/op next to 900 ns/op.
The default output unit is seconds. For a fast method in AverageTime mode, that produces tiny values such as 5.5E-8 s/op. This is a common reason for confusing first results.
You can override the unit from the command line with -tu:
java -jar target/benchmarks.jar ModesBenchmark -tu usThe accepted values include ns, us, ms, s, m, h and d.
Setting modes without annotations
Command-line options override annotations. This lets you try another mode without recompiling:
java -jar target/benchmarks.jar SumBenchmark -bm avgt -tu nsThe same options exist in the Runner API:
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Mode;
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 ModeRunner {
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(ModesBenchmark.class.getSimpleName())
.mode(Mode.AverageTime)
.timeUnit(TimeUnit.NANOSECONDS)
.forks(1)
.build();
new Runner(options).run();
}
}Common errors
- Comparing different modes. A throughput score and an average-time score are not in the same unit. Convert them, or rerun both in one mode.
- Reading the wrong direction. Higher is better for throughput. Lower is better for every time-based mode.
- Leaving the default unit. Seconds per operation produce numbers in scientific notation. Set
@OutputTimeUnit. - Using
SingleShotTimefor steady-state work. The result describes a cold call, not the speed of compiled code. - Trusting the mean for latency. Use
SampleTimeand read the percentiles when slow outliers matter. - Using
Mode.Allcasually. It runs every mode, so the run takes several times longer, and most of the output goes unused.
Exercise
A benchmark class is annotated with @BenchmarkMode(Mode.Throughput) and @OutputTimeUnit(TimeUnit.MILLISECONDS). One method reports a score of 2 000 000. Another class, using Mode.AverageTime with TimeUnit.NANOSECONDS, runs equivalent code and reports 480. State the unit of each score, and say which code is faster.
Show answer
The first score is 2 000 000 ops/ms. The second is 480 ns/op. Convert one to the other: 2 000 000 ops/ms is 2 000 000 000 ops/s, which is 0.5 ns per operation. That seems implausibly fast for real work, which suggests the first benchmark may have been optimized away (for example by dead-code elimination). If both numbers were trustworthy, the first would be faster, because 0.5 ns/op is less than 480 ns/op. Before comparing, check that both benchmarks consume their results.
Exercise
You want to know how long the very first call to a method takes in a fresh JVM, and you need a stable estimate. Which mode do you choose, and how do you get a stable estimate from calls that are each noisy?
Show answer
Use Mode.SingleShotTime (-bm ss) so each iteration times exactly one call, with no warmup (-wi 0). Run many forks (for example -f 20), so every measurement starts in a new JVM with unoptimized code. JMH then reports the mean and error across those forks.