Sub topic 13
Running benchmarks from the command line and from code
This chapter assumes you have built a JMH project with the Maven archetype and written at least one @Benchmark method such as SumBenchmark. You should be comfortable with the command line and with annotations. It covers three things: selecting and configuring runs with command-line flags, driving the same runs from Java code, and the rules for which setting wins when the same option is given in more than one place.
What happens when you run the jar
The archetype's mvn clean verify produces target/benchmarks.jar. This is a self-contained jar. It contains your compiled benchmarks, the JMH classes, and the generated benchmark code that annotation processing created at compile time. Its main class is org.openjdk.jmh.Main, so running the jar starts the JMH launcher.
The launcher does not measure anything itself. For each benchmark, it starts one or more fresh forked JVMs (see the previous chapter on forks). Each fork runs warmup and measurement iterations and reports back to the launcher. The launcher then prints the summary table.
Selecting benchmarks
Any argument without a leading dash is a regular expression. JMH matches it against the fully qualified benchmark name, which has the form package.Class.method.
# every benchmark in the project
java -jar target/benchmarks.jar
# every benchmark in one class
java -jar target/benchmarks.jar SumBenchmark
# one method, matched by a regex on the full name
java -jar target/benchmarks.jar 'SumBenchmark\.sum'
# list what would run, without running it
java -jar target/benchmarks.jar -lBecause the pattern is a regex, an unescaped . matches any character. A short pattern such as Sum also matches any other class whose name contains Sum. Run -l first when you are unsure what a pattern selects. The option -lp lists benchmarks together with their @Param fields and default values.
Overriding annotation settings
Every setting you put on a class in annotations can be overridden at run time. The most useful flags are:
| Flag | Meaning | Annotation it overrides |
|---|---|---|
| `-wi N` | Warmup iterations | `@Warmup(iterations)` |
| `-i N` | Measurement iterations | `@Measurement(iterations)` |
| `-w 2s` | Time per warmup iteration | `@Warmup(time)` |
| `-r 2s` | Time per measurement iteration | `@Measurement(time)` |
| `-f N` | Number of forks | `@Fork` |
| `-t N` | Number of threads | `@Threads` |
| `-bm avgt` | Benchmark mode (`thrpt`, `avgt`, `sample`, `ss`, `all`) | `@BenchmarkMode` |
| `-tu ns` | Output time unit | `@OutputTimeUnit` |
| `-p size=100` | Value for a `@Param` field | `@Param` |
| `-prof gc` | Add a profiler | none |
| `-rf json -rff out.json` | Result format and result file | none |
A realistic invocation combines several of them:
java -jar target/benchmarks.jar SumBenchmark -p size=10000 -wi 3 -i 5 -f 1 -prof gc -rf json -rff sum.jsonThis runs only the 10 000-element case. It does three warmup iterations, five measurement iterations and one fork, attaches the GC profiler, and writes machine-readable results to sum.json. The JSON file is the right input for scripts or charting tools. The console table is for reading by hand.
You can pass several values to -p by separating them with commas, as in -p size=100,10000. JMH then runs each value as a separate benchmark case.
Precedence
When the same setting appears in several places, the most specific source wins:
- Command-line flags (highest priority).
- Options set through the
RunnerAPI in code. - Annotations on the method.
- Annotations on the class.
- JMH defaults (lowest priority).
The practical consequence is that you can leave annotations as sensible defaults for the team and shorten a run on your laptop with -wi 1 -i 2 -f 1. Numbers from such a shortened run are only a smoke test. Do not compare them with a full run.
Passing JVM arguments
Each fork is a separate JVM, so java -Xmx2g -jar target/benchmarks.jar sets the heap size of the launcher only, not of the forks. To change the forks, use -jvmArgs "-Xmx2g". Use -jvmArgsAppend to add flags to the ones already set in @Fork(jvmArgs = ...) instead of replacing them. Benchmarks that compare garbage collectors or heap sizes depend on this, so check the flags with -v EXTRA or by looking at the "VM options" line in the output header.
Running from Java code
The Runner API starts the same machinery from a main method. This is convenient when you want to run from an IDE, select benchmarks in code, or post-process the results.
package org.sample;
import java.util.Collection;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.results.format.ResultFormatType;
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())
.param("size", "100")
.warmupIterations(3)
.measurementIterations(5)
.forks(1)
.addProfiler(GCProfiler.class)
.resultFormat(ResultFormatType.JSON)
.result("target/jmh-result.json")
.build();
Collection<RunResult> results = new Runner(options).run();
System.out.println("Benchmark cases run: " + results.size());
}
}include takes the same regex as the command line. Using SumBenchmark.class.getSimpleName() keeps the selection correct if you rename the class with an IDE refactoring. run() returns one RunResult per benchmark and parameter combination, so the size=100 filter above yields one result.
If you want your own main to accept the usual flags, pass args through instead of building options by hand:
import org.openjdk.jmh.runner.options.CommandLineOptions;
new Runner(new CommandLineOptions(args)).run();IDE gotchas
- JMH generates benchmark code at compile time through an annotation processor. The IDE must run annotation processing, or the run fails with a message that the benchmark list
META-INF/BenchmarkListis missing. Delegating the build to Maven, or enabling annotation processing for the project, fixes this. - The forked JVM needs the same classpath as the launcher. In an IDE this normally works, but a custom launcher or a restricted classpath, such as a manifest-only jar, can break it.
- An IDE adds its own agents and debug flags to the launcher JVM. Treat IDE runs as a way to check that a benchmark works. Take the numbers you report from
java -jar target/benchmarks.jaron a quiet machine.
Common errors
- "No benchmarks to run": the regex matched nothing, or the jar was built before you added the benchmark. Run
-land rebuild withmvn clean verify. - Wrong benchmarks selected: an unescaped
.or a short name matched more than you meant. Anchor the pattern, for example'^org\.sample\.SumBenchmark\.sum$'. - A
@Paramvalue is ignored: the name after-pmust match the field name exactly, and the field must bepublicor accessible to the generated code. - Results differ between two runs of the same command: check that nothing else is using the CPU. Also compare the reported error values (covered in the next chapter) before concluding that a change made a difference.
Exercise
You run java -jar target/benchmarks.jar SumBenchmark -i 10. SumBenchmark has @Measurement(iterations = 5, time = 1) and the Runner in your IDE sets .measurementIterations(3). How many measurement iterations does the command-line run perform, and how would you run only the size=10000 case with one fork and the GC profiler?
Show answer
It performs 10 measurement iterations, because command-line flags override both the Runner API and annotations. The time = 1 setting from the annotation still applies, since you did not override it. To run the 10 000-element case with one fork and the GC profiler, use: java -jar target/benchmarks.jar SumBenchmark -p size=10000 -f 1 -prof gc.
Exercise
Why does java -Xmx2g -jar target/benchmarks.jar not change the heap size that your benchmark code sees, and what should you use instead?
Show answer
JMH runs each benchmark in a forked JVM, and the -Xmx2g flag applies only to the launcher JVM. Pass the flag to the forks with -jvmArgs "-Xmx2g", or with -jvmArgsAppend to add it to the flags already set in @Fork.