
If you measure the runtime of Java code with a stopwatch – figuratively speaking, i.e., with System.currentTimeMillis() or System.nanoTime() – you also measure the JIT compiler, the garbage collector, and the clock itself. And often the stopwatch measures code that the JIT compiler has long since optimized away. The Java Microbenchmark Harness, JMH for short, is a tool from the OpenJDK project that measures in such a way that most of these disturbances don’t distort the result – and that lets you detect the remaining ones.
In this article, you will learn:
- why a measurement with
System.nanoTime()– and even more so withSystem.currentTimeMillis()– is misleading for short code, - how to set up a JMH project – and which trap every new project has run into since Java 23,
- how to write your first benchmark, run it, and read its output,
- what benchmark modes, forks, warm-up iterations, state objects, and parameters are,
- what the JIT compiler does to a benchmark and how you can detect it,
- how to use profilers to find out why a number is what it is,
- and what you need to watch out for so that two measurements are comparable.
The Examples in This Article
All benchmarks and programs in this article are in the GitHub repository java-jmh. The repository is also the project that the section Setting Up a JMH Project describes.
Almost all examples revolve around the same operation: converting an int into a String with Integer.toString(). It takes a few nanoseconds – short enough for every disturbance of the measurement, from the JIT compiler to the clock, to show up in the numbers. The article How to Convert int to String measures how fast the different ways of this conversion are.
I measured with JMH 1.37 and Java 27 on a MacBook Pro with an Apple M5 Pro. JMH 1.37 is from August 2023 and is still the current version on Maven Central.
Measuring Time with System.nanoTime() – and Why It Misleads
Before we get to JMH, let’s look at what happens without JMH. The problems that JMH solves are most obvious in a measurement that does not solve them.
The Stopwatch
The following program Stopwatch takes the time before and after a loop with one million conversions and divides the difference by the number of calls:
public class Stopwatch {
private static final int CALLS = 1_000_000;
void main() {
long checksum = 0;
long start = System.nanoTime();
for (int i = 0; i < CALLS; i++) {
checksum += Integer.toString(i).length();
}
long time = System.nanoTime() - start;
System.out.printf(
"%.1f ns per call (checksum: %d)%n", (double) time / CALLS, checksum);
}
}
The checksum adds up the lengths of all strings and is printed at the end. Without it, the JIT compiler would remove the conversion completely or partially, as its result is not used. What happens then is shown in the section The Unused Result.
Three runs of the program, each in a new JVM, print:
11.9 ns per call (checksum: 5888890)
9.3 ns per call (checksum: 5888890)
9.0 ns per call (checksum: 5888890)
Three runs, three numbers, and the first is 32% above the last. Which one is right? None of them measures only the conversion – the section What the Stopwatch Also Measures shows what else they measure.
nanoTime() or currentTimeMillis()?
Java offers two clocks, and only one of them is meant for measuring time:
| Method | What it returns | What for |
|---|---|---|
System.currentTimeMillis() | the time of day, in milliseconds since January 1, 1970; follows the system clock, even when it is adjusted – manually or when synchronizing with a time server | timestamps, date and time |
System.nanoTime() | a time in nanoseconds with an arbitrary origin; only the difference between two values has a meaning | measuring elapsed time |
According to the Javadoc, nanoTime() can only be used to measure elapsed time and is not related to the time of day. That is exactly what you need for a measurement. currentTimeMillis(), on the other hand, jumps when the system clock is adjusted – manually or automatically, when the operating system synchronizes it with a time server via NTP – and a measurement then includes the jump.
What the Stopwatch Also Measures
The program StopwatchRounds performs the same measurement 30 times in a row in one JVM:
Round 1: 9.5 ns per call (checksum: 5888890)
Round 2: 7.7 ns per call (checksum: 5888890)
Round 3: 4.7 ns per call (checksum: 5888890)
Round 4: 3.3 ns per call (checksum: 5888890)
Round 5: 3.8 ns per call (checksum: 5888890)
Round 6: 3.2 ns per call (checksum: 5888890)
Round 7: 3.6 ns per call (checksum: 5888890)
Round 8: 3.3 ns per call (checksum: 5888890)
Round 9: 4.4 ns per call (checksum: 5888890)
Round 10: 5.3 ns per call (checksum: 5888890)
Round 11: 5.6 ns per call (checksum: 5888890)
Round 12: 5.7 ns per call (checksum: 5888890)
Round 13: 5.7 ns per call (checksum: 5888890)
Round 14: 5.6 ns per call (checksum: 5888890)
Round 15: 5.6 ns per call (checksum: 5888890)
Round 16: 5.5 ns per call (checksum: 5888890)
Round 17: 3.3 ns per call (checksum: 5888890)
Round 18: 3.4 ns per call (checksum: 5888890)
Round 19: 3.4 ns per call (checksum: 5888890)
Round 20: 3.1 ns per call (checksum: 5888890)
Round 21: 3.1 ns per call (checksum: 5888890)
Round 22: 3.8 ns per call (checksum: 5888890)
Round 23: 3.9 ns per call (checksum: 5888890)
Round 24: 3.3 ns per call (checksum: 5888890)
Round 25: 3.3 ns per call (checksum: 5888890)
Round 26: 3.4 ns per call (checksum: 5888890)
Round 27: 3.4 ns per call (checksum: 5888890)
Round 28: 3.5 ns per call (checksum: 5888890)
Round 29: 3.4 ns per call (checksum: 5888890)
Round 30: 3.6 ns per call (checksum: 5888890)
Two disturbances show up here.
The first shows in rounds 1 to 3. The JVM initially executes the code in the interpreter and only gradually translates it into machine code with the JIT compiler. The program Stopwatch from the section The Stopwatch measured only a single round – exactly this warm-up phase. Its 9.0 to 11.9 ns are therefore close to the 9.5 ns that StopwatchRounds measures in its first round, and far above the 3.2 to 3.8 ns that StopwatchRounds measures in rounds 4 to 8.
You can see the second disturbance in rounds 9 to 16. The code is fully compiled and still runs slower, in rounds 12 and 13, at 5.7 ns, 73% slower than in round 8. A run with -Xlog:gc shows what happens before round 9: The garbage collector grows the heap from 96 to 288 MB, and the slow phase lasts until the next GC run.
If you start the JVM with a fixed heap of 4 GB and the option -XX:+AlwaysPreTouch, which writes to the whole heap once at startup, all rounds from the third on stay between 3.2 and 4.2 ns. So the stopwatch also measures how the JVM manages its heap.
The Order Decides Too
What the second disturbance – the slower code after the heap grows – means for a comparison is shown by the program StopwatchTwoCandidates. It measures two ways of converting, Integer.toString(i) and String.valueOf(i), ten rounds each, one after the other in the same JVM, and prints the time of the tenth round of each. With the argument reverse, it measures in reverse order:
Integer.toString(i): 6.1 ns per call in round 10 (checksum: 58888900)
String.valueOf(i) : 4.0 ns per call in round 10 (checksum: 58888900)
String.valueOf(i) : 6.1 ns per call in round 10 (checksum: 58888900)
Integer.toString(i): 3.7 ns per call in round 10 (checksum: 58888900)
The candidate measured first is the slower one in both orders – in all three runs. Yet String.valueOf(i) calls Integer.toString(i) internally; both candidates execute the same code. The tenth round of the first candidate falls into the slow phase that StopwatchRounds shows between rounds 9 and 16. The tenth round of the second candidate is the twentieth round of the JVM.
Which candidate is faster is decided here by the order, not by the code.
The Unused Result
A third disturbance shows up when you don’t use the result. The program StopwatchLogarithm measures one million calls of Math.log() and adds the results to a checksum – just as Stopwatch does with the lengths of the strings:
double checksum = 0;
for (int i = 1; i <= CALLS; i++) {
checksum += Math.log(i);
}
From round 3 on, a call takes 3.1 to 3.2 ns. The program StopwatchUnusedResult runs the same loop, but doesn’t use the result:
for (int i = 1; i <= CALLS; i++) {
Math.log(i);
}
StopwatchUnusedResult prints these ten rounds:
Round 1: 1.33 ns per call
Round 2: 1.06 ns per call
Round 3: 0.64 ns per call
Round 4: 0.25 ns per call
Round 5: 0.27 ns per call
Round 6: 0.23 ns per call
Round 7: 0.24 ns per call
Round 8: 0.22 ns per call
Round 9: 0.24 ns per call
Round 10: 0.23 ns per call
From round 4 on, a call takes 0.22 to 0.27 ns – less than a tenth of the 3.1 to 3.2 ns with checksum. The JIT compiler has recognized that the result is never used and has therefore optimized the calculation away.
The Resolution of the Clock
That leaves the question of why you don’t simply measure a single call. The program ClockResolution calls System.nanoTime() until the value changes and counts by how much it jumps. On the M5 Pro, it was 41 or 42 ns in 99.9% of ten million attempts.
A clock that ticks in steps of 41 ns cannot measure a call of four nanoseconds. JMH solves this by taking the time only at the beginning and at the end of a whole iteration that lasts several seconds – more on this in the section A Look at the Generated Code.
When a Stopwatch Is Enough
For everything that runs only once and takes milliseconds or longer, System.nanoTime() is the right tool: an HTTP request, a batch job, the startup time of an application. There, you want to measure exactly this one run – including everything the JVM does along the way.
But as soon as you want to know how long a short piece of code takes in the warmed-up state, or you want to compare two variants, you need JMH.
What Is JMH?
JMH is a framework that measures short pieces of code in such a way that most of the disturbances from the previous section – the warm-up phase, the influence of the order, optimizing away unused results, and the coarse resolution of the clock – don’t distort the result. It is an OpenJDK project and is on GitHub under openjdk/jmh.
You write a method with the annotation @Benchmark, and JMH takes care of the rest:
- During compilation, an annotation processor – a plugin for the
javaccompiler – generates a measurement loop around each benchmark method. - For each measurement, JMH starts a new JVM, a so-called fork. This way, no benchmark inherits the compiler decisions and the heap of another benchmark.
- In each fork, JMH first calls the method for a while without measuring. In this warm-up phase, the JIT compiler translates the code.
- Then it measures in several iterations of a few seconds how often the method is called.
- Finally, it prints the mean of all iterations – together with an error interval that shows how much the measurements scatter.
A microbenchmark thus answers a narrow question: How long does this piece of code take under these conditions? Whether your application gets faster if you replace the code is something it doesn’t answer. For that, you have to observe the application itself, e.g., with the Java Flight Recorder.
Setting Up a JMH Project
JMH recommends creating benchmarks in a separate Maven project that includes your application code as a dependency. The quickest way to create such a project is with the Maven archetype of JMH.
With the Maven Archetype
The following command is taken from the JMH README:
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample \
-DartifactId=test \
-Dversion=1.0
The command creates a project with an empty benchmark class MyBenchmark in the directory test. The generated pom.xml contains:
- the dependency
jmh-core– the runtime library of JMH, - the dependency
jmh-generator-annprocesswith the scopeprovided– the annotation processor that generates the measurement loops, - the Maven Shade Plugin, which packs your code and JMH into a single executable file
target/benchmarks.jar.
Two details in the Maven archetype are outdated: The pom.xml compiles for Java 8 (javac.target is 1.8), and it uses the maven-compiler-plugin in version 3.8.0. Set javac.target to the Java version you work with and the plugin to the current version (as of November 30, 2026: 3.16.0).
The Trap Since Java 23: Unable to find the resource
On a current JDK, the freshly generated project builds with mvn clean package without any error message. When you start it, however, it aborts:
$ java -jar target/benchmarks.jar
Exception in thread "main" java.lang.RuntimeException: ERROR: Unable to find the resource: /META-INF/BenchmarkList
at org.openjdk.jmh.runner.AbstractResourceReader.getReaders(AbstractResourceReader.java:98)
at org.openjdk.jmh.runner.BenchmarkList.find(BenchmarkList.java:124)
at org.openjdk.jmh.runner.Runner.internalRun(Runner.java:252)
at org.openjdk.jmh.runner.Runner.run(Runner.java:208)
at org.openjdk.jmh.Main.main(Main.java:71)
The annotation processor should have written the missing file META-INF/BenchmarkList – but it didn’t run at all. Since Java 23, javac no longer starts an annotation processor just because it is on the class path. Java 21 and 22 still printed a note that a future version might change this; Java 23 silently skips the processor.
The solution: You have to name the annotation processor explicitly in the configuration of the maven-compiler-plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.16.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
With this entry, the archetype project builds a benchmarks.jar on Java 27 that you can start. The pom.xml of the example repository already contains the annotationProcessorPaths entry.
In an Existing Project
If you want to add JMH to an existing Maven project, you need the same three building blocks as in the archetype: the two dependencies jmh-core and jmh-generator-annprocess, the annotationProcessorPaths entry from the previous listing, and the Shade Plugin with org.openjdk.jmh.Main as the main class. You can copy the Shade Plugin from the pom.xml of the example repository.
For Gradle, the JMH project itself provides no support. The README refers to the community plugin jmh-gradle-plugin with the plugin ID me.champeau.jmh.
Where the Benchmarks Belong
In a separate Maven project, as JMH recommends, mvn package builds the benchmarks.jar, and you start it independently of the build.
It may seem natural to put benchmarks under src/test and start them from a JUnit test. But then they run with every test run – and in the JVM that the build has configured for the tests.
JMH passes most of this JVM’s options on to its forks. If the build checks test coverage, e.g., with JaCoCo, the benchmark then measures the code instrumented by JaCoCo.
The First Benchmark
The first benchmark measures the conversion with Integer.toString() and leaves everything else to the JMH defaults: five forks with five warm-up and five measurement iterations of ten seconds each. It is in the class IntToStringBenchmark of the example repository:
package eu.happycoders.jmh;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class IntToStringBenchmark {
private int number = 1_234_567;
@Benchmark
public String intToString() {
return Integer.toString(number);
}
}
Two things look superfluous at first glance, but they are anything but.
The method returns the string. JMH uses the return value, so the JIT compiler cannot remove the conversion – more on this in the section Dead Code Elimination.
And the number comes from a field, not from a constant. The section Constant Folding shows why. However, a benchmark class may only have a field if it is annotated with @State. Without the annotation, the build aborts:
error: Field "number" is declared within a class not having @State annotation. This is prohibited because it can result in unspecified behavior.
What @State and Scope.Benchmark mean is explained in the section State: Where the Test Data Comes From.
The annotation processor checks further rules during compilation. A benchmark class must be in a package:
error: Benchmark class should have package other than default.
And a benchmark method must be public:
error: @Benchmark method should be public.
You build the benchmark with mvn clean package and start it with java -jar and a regular expression that selects the benchmark:
java -jar target/benchmarks.jar 'eu\.happycoders\.jmh\.IntToStringBenchmark'
The run takes 8 minutes and 20 seconds – why it takes so long is explained in the section Forks, Warm-up, and Iterations. At the end, JMH prints this table:
Benchmark Mode Cnt Score Error Units
IntToStringBenchmark.intToString thrpt 25 214750906.087 ± 1175685.582 ops/s
So the M5 Pro manages just under 215 million conversions per second, 4.66 ns per conversion. What the other columns mean is explained in the next section.
But first a word about the four lines with which every JVM of the run starts its output on Java 27:
WARNING: A terminally deprecated method in sun.misc.Unsafe has been called
WARNING: sun.misc.Unsafe::objectFieldOffset has been called by org.openjdk.jmh.util.Utils (file:/Users/sven/Projects/HappyCoders/git-articles/java-jmh/target/benchmarks.jar)
WARNING: Please consider reporting this to the maintainers of class org.openjdk.jmh.util.Utils
WARNING: sun.misc.Unsafe::objectFieldOffset will be removed in a future release
These are warnings, not errors. Since Java 24, the JVM reports the first call of a memory access method from sun.misc.Unsafe, and JMH 1.37 uses one of them.
Running from the IDE
You can also start a benchmark from a main() method, e.g., in the IDE. The class BenchmarkRunner in the example repository starts the first benchmark with one fork:
public class BenchmarkRunner {
void main() throws RunnerException {
String benchmark = IntToStringBenchmark.class.getName();
Options options = new OptionsBuilder().include(benchmark).forks(1).build();
new Runner(options).run();
}
}
forks(1) makes JMH start only one fork instead of the default five. You can also set the other settings that this article presents later via methods of OptionsBuilder, e.g., warmupIterations() or measurementIterations(). Before you start BenchmarkRunner, Maven must have built the project, because JMH needs the file META-INF/BenchmarkList here, too.
However, the JMH README advises against running benchmarks from the IDE: The environment there cannot be controlled – the IDE indexes, compiles, and runs on the same cores. For IntelliJ IDEA, there is also the community plugin JMH Java Microbenchmark Harness. With it, you start a benchmark without a main() method directly from the benchmark class – like a JUnit test: a single @Benchmark method or all benchmarks of the class.
I recommend the IDE for a quick try and the command line for every number you pass on.
Reading the Output
During the run, JMH first prints the settings of the benchmark, then the iterations of each fork, and at the end the result. It formats the numbers in the language of the JVM; the outputs in this article show them as a JVM with an English locale prints them, with a decimal point.
The Settings
Before the first fork of a benchmark, there are these lines:
# JMH version: 1.37
# VM version: JDK 27, OpenJDK 64-Bit Server VM, 27+35-2325
# VM invoker: /Users/sven/.sdkman/candidates/java/27.0.0+35-open/bin/java
# VM options: <none>
# Blackhole mode: compiler (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: eu.happycoders.jmh.IntToStringBenchmark.intToString
These lines answer the questions of someone who wants to reproduce your numbers: which JMH and JVM version, which java binary, which JVM options, how many iterations of which duration, how many threads, which mode. I explain the line Blackhole mode in the section The Blackhole.
The Iterations of a Fork
Then come the warm-up and measurement iterations of each fork. The first of five forks:
# Run progress: 0.00% complete, ETA 00:08:20
# Fork: 1 of 5
# Warmup Iteration 1: 216975609.190 ops/s
# Warmup Iteration 2: 221910095.619 ops/s
# Warmup Iteration 3: 221751361.540 ops/s
# Warmup Iteration 4: 220579584.502 ops/s
# Warmup Iteration 5: 218302698.263 ops/s
Iteration 1: 217348528.639 ops/s
Iteration 2: 215935331.237 ops/s
Iteration 3: 218067325.224 ops/s
Iteration 4: 217746270.901 ops/s
Iteration 5: 217152759.698 ops/s
Note the first warm-up iteration: It is hardly slower than the others. For such a short method, the JIT compiler is done after fractions of a second, and the ten seconds of the first iteration hide that. Here, you could therefore shorten the warm-up phase – the section The Defaults and What You Can Shorten shows how. If, on the other hand, the warm-up values change until the last iteration, you should extend the warm-up phase.
The Result: Score and Error
After the last fork, JMH summarizes all measurement iterations:
Result "eu.happycoders.jmh.IntToStringBenchmark.intToString":
214750906.087 ±(99.9%) 1175685.582 ops/s [Average]
(min, avg, max) = (212368978.919, 214750906.087, 218067325.224), stdev = 1569506.615
CI (99.9%): [213575220.506, 215926591.669] (assumes normal distribution)
The line with [Average] is the result: 214750906.087 is the mean of all 25 measurement iterations, and after ±(99.9%) comes the error, which I explain below with the table.
The line (min, avg, max) shows how far the individual iterations scatter. The slowest managed 212.4 million operations per second, the fastest 218.1 million. stdev is the standard deviation of the 25 values: 1.57 million, i.e., 0.73% of the mean.
The line CI (99.9%) gives the 99.9% confidence interval: 213.6 to 215.9 million operations per second. JMH calculates it under the assumption that the measured values are normally distributed.
Then comes the table from the previous section:
Benchmark Mode Cnt Score Error Units
IntToStringBenchmark.intToString thrpt 25 214750906.087 ± 1175685.582 ops/s
The columns mean:
Mode: the benchmark mode, herethrptfor throughput (see next section).Cnt: the number of measurement iterations from which the value is averaged – five forks times five iterations makes 25.Score: the mean of these 25 iterations.Error: half the width of the 99.9% confidence interval from the lineCI (99.9%). Score ± error therefore gives exactly this interval.Units: the unit, here operations per second.
The error here is only 0.55% of the mean. This means: The actual throughput of the method on this machine is, with high certainty, at most 1.2 million operations per second above or below the measured 214.8 million. The random fluctuations between the iterations therefore hardly matter for this result.
As a general rule for comparing two results: If their confidence intervals don’t overlap, the difference is real. If they overlap, you shouldn’t claim a difference. With errors of around 0.55% as here, you can thus detect differences of just over one percent or more.
The “REMEMBER” Notice
Between the last fork and the table, JMH prints this notice in every run:
REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.
A number is only worth something once you can explain why it is what it is. The tools for this – baseline, profilers, a controlled environment – are covered in the sections What the JIT Compiler Does to a Benchmark, Profilers, and Numbers You Can Rely On.
Benchmark Modes and Time Units
By default, JMH measures the throughput in operations per second. With @BenchmarkMode, you choose a different mode – and with @OutputTimeUnit the unit:
| Mode | Short form | What JMH prints | What for |
|---|---|---|---|
Mode.Throughput | thrpt | calls per time unit | the default; higher values are better |
Mode.AverageTime | avgt | average time per call | short operations whose duration you are interested in |
Mode.SampleTime | sample | distribution of the times of individual calls with percentiles | when outliers matter, e.g., latencies |
Mode.SingleShotTime | ss | time of a single call or of a batch of calls per iteration | cold code, e.g., the first call after startup |
Mode.All | all | all four modes one after the other | for trying things out |
All further benchmarks in this article measure the average time in nanoseconds:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
For the first measurement, 214,750,906 operations per second correspond to 4.66 ns per operation – 1,000,000,000 ns divided by 214,750,906 operations.
Batch Size: When Each Call Measures Something Different
The modes Throughput and AverageTime assume that every call does the same amount of work. For some operations, this is not the case, e.g., when appending to an ArrayList that gets longer with every call – and now and then grows its internal array.
The class BatchSizeBenchmark measures this appending in two ways: once as before for one second, and once in batches with a fixed number of calls:
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(
value = 3,
jvmArgsAppend = {"-Xms12g", "-Xmx12g"})
@State(Scope.Thread)
public class BatchSizeBenchmark {
private static final int BATCH_SIZE = 10_000;
private List<Integer> list;
@Setup(Level.Iteration)
public void setup() {
list = new ArrayList<>();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
public boolean addForOneSecond() {
return list.add(42);
}
@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@Warmup(iterations = 100, batchSize = BATCH_SIZE)
@Measurement(iterations = 50, batchSize = BATCH_SIZE)
public boolean addInBatches() {
return list.add(42);
}
}
The method addForOneSecond() appends elements for one second to a list that is empty at the beginning of each iteration. How long the list gets is determined not by the benchmark, but by the speed of the machine: At 2.1 ns per call, it is around 475 million elements after one second. With a heap of 4 GB, the benchmark therefore aborts with an OutOfMemoryError already in the second measurement iteration. That is why the class gives its forks 12 GB.
The method addInBatches(), on the other hand, measures in the mode SingleShotTime with a batch size of 10,000: JMH calls the method exactly 10,000 times per iteration and measures the time for it. Each iteration starts with an empty list, and each measured iteration comprises the same 10,000 calls.
Both methods specify their warm-up iterations, but for different reasons: addForOneSecond(), like all benchmarks in this article, shortens the warm-up from the default five iterations of ten seconds each to three iterations of one second each. That is enough here: Even the third warm-up iteration, at 2.05 to 2.08 ns in all three forks, is within the 1.9 to 2.3 ns of the measurement iterations.
For addInBatches(), the specification is mandatory, because in the mode SingleShotTime, JMH doesn’t warm up at all without it. There are 100 iterations because each iteration is short: A batch of 10,000 calls initially takes around 320,000 ns, about 75,000 ns after seven iterations, and reaches its final value of around 24,000 ns only from the 26th or 27th iteration on. After that, the time doesn’t change anymore apart from individual outliers. 100 iterations leave enough reserve for this.
The results:
Benchmark Mode Cnt Score Error Units
BatchSizeBenchmark.addForOneSecond avgt 15 2.105 ± 0.163 ns/op
BatchSizeBenchmark.addInBatches ss 150 26903.633 ± 1406.336 ns/op
In the mode SingleShotTime, the score is the time for the whole batch: 26,904 ns for 10,000 calls, i.e., 2.7 ns per call. The number applies to a list that grows from 0 to 10,000 elements – the 2.1 ns from addForOneSecond(), on the other hand, to a list whose length depends on how often the machine can call add() in one second.
Forks, Warm-up, and Iterations
A JMH run is structured in three levels:
- A fork is a separate JVM that JMH starts for the measurement.
- In each fork, the warm-up iterations run first, whose results JMH discards, then the measurement iterations.
- In each iteration, JMH calls the benchmark method as often as fits into the iteration time – or, in the mode
SingleShotTime, exactly as often as the batch size specifies. Each call is an invocation.
The following diagram shows a run with the default settings: at the top the five forks, in the middle the iterations of the first fork – five warm-up and five measurement iterations of ten seconds each – and at the bottom the calls of the benchmark method in one measurement iteration. Only the measurement iterations count toward the result: five forks with five measurement iterations each, i.e., 25.
Why Several Forks?
Each JVM makes its own decisions: when the JIT compiler translates which method, how it optimizes it, where the objects are located in the heap. The five forks of the first benchmark came to 217.3, 215.0, 213.2, 214.0, and 214.3 million operations per second on average over their measurement iterations. The fastest fork was thus 1.9% above the slowest.
With only one fork, you would have gotten one of these numbers and would not have learned how far the next JVM is from it. The standard deviation of the iterations within a fork was between 0.7 and 0.9 million operations per second, that of the five fork means between the forks 1.5 million. So more iterations don’t replace additional forks.
The Defaults and What You Can Shorten
Five forks times ten iterations times ten seconds make 500 seconds, i.e., 8 minutes and 20 seconds per benchmark method. For a class with six methods, that would be almost 50 minutes.
From the next section on, the benchmarks in this article run with three forks, three warm-up and five measurement iterations of one second each – 24 instead of 500 seconds per method:
@Fork(3)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
That is enough for methods in the nanosecond range whose warm-up values are stable after the first iteration. I still stick with three forks – they show you whether the result also holds in the next JVM.
Instead of using annotations, you can also set these values on the command line at startup, without rebuilding the benchmark – e.g., for a quick test run with only one fork:
-ffor the number of forks,-wiand-ifor the number of warm-up and measurement iterations,-wand-rfor their duration.
The section Annotation or Command Line shows which one applies when annotation and command line contradict each other.
More Settings of @Fork
Besides the number of forks, @Fork has further settings:
- You pass options for the JVM of the forks, e.g., the heap size as in the section Batch Size, with
@Fork(jvmArgsAppend = …)or on the command line with-jvmArgsAppend. - With
@Fork(warmups = 1)or-wf 1, JMH starts an additional fork before the measurement forks, whose results it discards; the number specifies how many such warm-up forks there are. They are not to be confused with warm-up iterations; by default, there are none. - A special case is
@Fork(0)or-f 0: Then JMH doesn’t start a fork at all, but measures in the JVM in which it runs itself. This mode is meant for stepping through a benchmark in the debugger – not for measuring.
State: Where the Test Data Comes From
A benchmark often needs inputs: e.g., a number, an array, or a list. You put these inputs into state objects – instances of classes with the annotation @State. JMH creates these instances itself and passes them to a benchmark method if it has a parameter of the state class’s type. The following class StateObjectBenchmark puts the number from the first benchmark into a separate state class Input:
public class StateObjectBenchmark {
@State(Scope.Thread)
public static class Input {
int number = 1_234_567;
}
@Benchmark
public String intToString(Input input) {
return Integer.toString(input.number);
}
}
You don’t create Input anywhere yourself: JMH creates the object automatically and passes it to intToString() on every call.
If the benchmark class itself is annotated with @State, like IntToStringBenchmark from the section The First Benchmark, it is its own state object. Then the benchmark method reads the inputs from its own fields and needs no parameter.
By default, JMH calls the benchmark method in a single thread. With @Threads or -t, it calls it simultaneously from several threads – more on this in the section Benchmarks with Multiple Threads. The scope in the @State annotation determines which of these threads share a state object:
Scope.Benchmark: all threads of the benchmark share a single state object.Scope.Thread: each thread gets its own state object.Scope.Group: all threads of a group share a state object (see also Benchmarks with Multiple Threads).
In a benchmark with only one thread, as JMH starts it by default, all three scopes behave the same.
A state class must be public, as an inner class also static, and it needs a public constructor without parameters. If you don’t declare a constructor – as with Input – the compiler generates one automatically. If one of the three requirements is missing, the annotation processor aborts, e.g.:
error: The @State annotation can only be applied to the classes having the default public constructor.
@Setup and @TearDown
A method in the state class annotated with @Setup prepares the state object, one annotated with @TearDown cleans it up. Both must be public. When they run is determined by the level:
| Level | Runs | What for |
|---|---|---|
Level.Trial (default) | once per fork, before the warm-up or after the last measurement iteration | test data that doesn’t change |
Level.Iteration | before or after each iteration | data that the benchmark changes, e.g., a growing list |
Level.Invocation | before or after each individual call | only for calls of a millisecond or more, see below |
BatchSizeBenchmark from the section Batch Size already uses such a method to start each iteration with an empty list:
@Setup(Level.Iteration)
public void setup() {
list = new ArrayList<>();
}
Whatever takes long to build and is only read by the benchmark – a large collection, a file, an application context – belongs in a @Setup method with Level.Trial in a state object with Scope.Benchmark. Then JMH builds it once per fork and not in every iteration. If the benchmark changes the data, you need Level.Iteration as in BatchSizeBenchmark.
Level.Invocation: Careful with Short Methods
Level.Invocation sounds like the solution for fresh test data on every call. For short methods, however, it distorts the result: So that the setup time is not measured, JMH has to frame every single call with two timestamps, instead of taking the time only at the beginning and at the end of the whole iteration as usual. These timestamps cost more than an operation of a few nanoseconds – and on the M5 Pro, as shown in the section The Resolution of the Clock, they tick in steps of 41 ns.
The Javadoc of Level.Invocation therefore begins with “WARNING: HERE BE DRAGONS! THIS IS A SHARP TOOL.” and considers the level usable only for calls of a millisecond or more. The article How to Convert int to String shows how far off a measurement can be with it: With Level.Trial, the same benchmark measures three times as many operations per second as with Level.Invocation.
Parameters with @Param
With @Param, you measure a benchmark for different input values without having to copy the benchmark method – you may know this from parameterized unit tests. The class SortedDataBenchmark from the section Test Data That Is Too Clean measures for two array sizes:
@Param({"1024", "1048576"})
private int size;
JMH sets the field to each of the values in turn and measures the benchmark separately for each value. If the state class has a @Setup method, the value is already available there – SortedDataBenchmark creates the arrays in the matching size in it:
@Setup
public void setup() {
shuffled = new Random(42).ints(size, 0, 256).toArray();
sorted = shuffled.clone();
Arrays.sort(sorted);
}
The values are strings in the annotation; JMH converts them into the type of the field. In the result table, they appear in a separate column with the name of the field in parentheses:
Benchmark (size) Mode Cnt Score Error Units
SortedDataBenchmark.shuffled 1024 avgt 15 261.621 ± 6.255 ns/op
SortedDataBenchmark.shuffled 1048576 avgt 15 1807467.661 ± 13454.652 ns/op
SortedDataBenchmark.sorted 1024 avgt 15 176.362 ± 0.987 ns/op
SortedDataBenchmark.sorted 1048576 avgt 15 183608.293 ± 2453.235 ns/op
On the command line, you override the values with -p, e.g., -p size=4096,65536.
If a benchmark has several parameters, JMH measures every combination. Three parameters with four values each, for example, result in 64 combinations.
What the JIT Compiler Does to a Benchmark
The JIT compiler optimizes a benchmark just like any other code. It removes what nobody uses and computes what it can already compute at compile time. In an application, this is desired – in a benchmark, it often makes you measure something other than you think.
The following benchmarks run with three forks, three warm-up and five measurement iterations of one second each.
The Baseline
How fast is a benchmark when it does nothing? The class BaselineBenchmark measures an empty method and one that only returns a field:
@Benchmark
public void empty() {
// Intentionally empty: measures the harness alone
}
@Benchmark
public int returnInput() {
return number;
}
The results:
Benchmark Mode Cnt Score Error Units
BaselineBenchmark.empty avgt 15 0.245 ± 0.018 ns/op
BaselineBenchmark.returnInput avgt 15 0.314 ± 0.030 ns/op
So a call through JMH costs a quarter of a nanosecond on the M5 Pro. If the method reads a field and returns it, it adds about 0.07 ns. With this yardstick, you can tell in the next two sections whether anything is left of the code in the method after the optimizations of the JIT compiler.
Dead Code Elimination
If the result of a calculation is not used, the JIT compiler may remove the calculation – this is called dead code elimination. The class DeadCodeBenchmark calls two methods without using their results:
@Benchmark
public void logDropped() {
Math.log(number);
}
@Benchmark
public void intToStringDropped() {
Integer.toString(number);
}
In addition, it measures the same calls with return and with a Blackhole (more on this in a moment). In the output, you recognize the three variants by the ending of the method name: Dropped without using the result, Returned with return, and Consumed with Blackhole:
Benchmark Mode Cnt Score Error Units
DeadCodeBenchmark.intToStringConsumed avgt 15 4.633 ± 0.021 ns/op
DeadCodeBenchmark.intToStringDropped avgt 15 3.607 ± 0.018 ns/op
DeadCodeBenchmark.intToStringReturned avgt 15 4.706 ± 0.085 ns/op
DeadCodeBenchmark.logConsumed avgt 15 3.097 ± 0.003 ns/op
DeadCodeBenchmark.logDropped avgt 15 0.244 ± 0.018 ns/op
DeadCodeBenchmark.logReturned avgt 15 3.093 ± 0.017 ns/op
At 0.244 ns, logDropped() is as fast as the empty method of the baseline. So the JIT compiler has removed Math.log() completely – the 3.1 ns of logConsumed() and logReturned() are the time the logarithm really takes.
For Integer.toString(), the JIT compiler removes less. intToStringDropped() takes 3.6 instead of 4.7 ns, i.e., 23% less time than with return, but is far above the baseline. The profiler -prof gc (see Profilers) shows what is missing: With the result discarded, the call allocates 24 instead of 48 bytes. So the JIT compiler has removed only part of the conversion. Such a benchmark delivers a plausible number that is wrong nonetheless – only the comparison with the variant with return or the Blackhole reveals the error.
The solution is the same in both cases: Return the result as in the first benchmark, or pass it to a Blackhole – more on this in the next section.
The Blackhole
With return, you can return only one result. If, however, a benchmark calculates several values, e.g., in a loop, you can pass each of these values to a blackhole – an object from JMH that accepts arbitrary values. To the JIT compiler, it looks as if these values were used. If you declare a parameter of type Blackhole in a benchmark method, JMH passes such an object to it when calling it:
@Benchmark
public void intToStringConsumed(Blackhole blackhole) {
blackhole.consume(Integer.toString(number));
}
With return and with Blackhole, the results in the table of the previous section are almost the same: 4.706 and 4.633 ns, 3.093 and 3.097 ns. JMH itself passes a returned value to a Blackhole.
The line Blackhole mode: compiler in the settings at the beginning of the output (see the section The Settings) means that JMH uses the JVM’s compiler blackholes. Since Java 17, the JIT compiler has had its own mechanism for this: At JVM startup, JMH registers an empty method as a blackhole. If the benchmark passes a value to this method, the JIT compiler must calculate the value completely – but it omits the call of this method itself, so that it costs no time.
Some benchmarks don’t measure a calculation, but how something changes with the amount of work – e.g., the amount of work per element from which a parallel stream pays off. For the work itself, Blackhole has the static method consumeCPU(): It executes as many computation steps as its argument specifies – with twice the value, it therefore computes about twice as long. The JIT compiler cannot remove these computation steps. The article about parallel streams uses it to generate the work per element.
Constant Folding
If the JIT compiler computes an expression at compile time because all inputs are fixed, this is called constant folding. The class ConstantFoldingBenchmark converts the same string as a literal, from a final field, and from a non-final field into a number – and the same number in the same three ways into a string. The variants for Integer.parseInt():
private final String finalText = "1234567";
private String text = "1234567";
@Benchmark
public int parseIntOfLiteral() {
return Integer.parseInt("1234567");
}
@Benchmark
public int parseIntOfFinalField() {
return Integer.parseInt(finalText);
}
@Benchmark
public int parseIntOfField() {
return Integer.parseInt(text);
}
The results:
Benchmark Mode Cnt Score Error Units
ConstantFoldingBenchmark.intToStringOfField avgt 15 4.531 ± 0.028 ns/op
ConstantFoldingBenchmark.intToStringOfFinalField avgt 15 4.359 ± 0.023 ns/op
ConstantFoldingBenchmark.intToStringOfLiteral avgt 15 4.368 ± 0.026 ns/op
ConstantFoldingBenchmark.parseIntOfField avgt 15 3.278 ± 0.011 ns/op
ConstantFoldingBenchmark.parseIntOfFinalField avgt 15 0.244 ± 0.018 ns/op
ConstantFoldingBenchmark.parseIntOfLiteral avgt 15 0.240 ± 0.001 ns/op
parseIntOfField() takes 3.3 ns for the conversion. parseIntOfLiteral() and parseIntOfFinalField(), on the other hand, are as fast as the empty method of the baseline at 0.240 and 0.244 ns: The JIT compiler has computed Integer.parseInt("1234567") once – and only returns the number 1,234,567.
That parseIntOfFinalField() reads the string from a field doesn’t change anything. Because the final field is initialized with a literal, javac already replaces every access to it with the literal; so the bytecode of parseIntOfFinalField() is the same as that of parseIntOfLiteral().
For Integer.toString(), on the other hand, the constant makes hardly any difference: 4.368 ns with the literal and 4.359 ns with the final field instead of 4.531 ns with the non-final field. Here, the JIT compiler only precomputes the length of the string. It still calculates the digits on every call, and it has to create the new String object on every call anyway.
So whether or not the JIT compiler precomputes a call with constant input depends on the called method – and to keep it from precomputing anything, every benchmark in this article reads its input from a non-final field.
Loops in the Benchmark Method
It may seem natural to write a loop yourself in a benchmark method to increase the time per call. That is not necessary, because JMH takes care of the repetition. If you still need the loop, e.g., because the benchmark iterates over a whole array, you tell JMH with @OperationsPerInvocation how many operations a call comprises. JMH then divides the measured time by this number.
The class LoopBenchmark fills numbers with 1,024 random numbers in its @Setup method. allNumbersInALoop() converts all these numbers on every call, oneNumberPerCall() only one for comparison:
private static final int SIZE = 1_024;
private int[] numbers;
private int index;
@Setup
public void setup() {
numbers = new Random(42).ints(SIZE).toArray();
}
@Benchmark
@OperationsPerInvocation(SIZE)
public void allNumbersInALoop(Blackhole blackhole) {
for (int number : numbers) {
blackhole.consume(Integer.toString(number));
}
}
@Benchmark
public String oneNumberPerCall() {
return Integer.toString(numbers[index++ & (SIZE - 1)]);
}
The fixed seed 42 for new Random() ensures that every fork gets the same random numbers. oneNumberPerCall() takes the next number from the array on every call. After the last one, index++ & (SIZE - 1) starts again with the first – this works with the bitwise AND because SIZE is a power of two.
The result of both methods:
Benchmark Mode Cnt Score Error Units
LoopBenchmark.allNumbersInALoop avgt 15 5.615 ± 0.125 ns/op
LoopBenchmark.oneNumberPerCall avgt 15 5.852 ± 0.024 ns/op
In this example, both values are close together. The 0.24 ns by which oneNumberPerCall() is slower correspond roughly to what a call through JMH costs according to the baseline.
In other benchmarks, the values can be far apart: In a loop, the JIT compiler may combine iterations, move calculations out of the loop, or parallelize them with SIMD instructions. Then you mainly measure the loop, not the operation in it. JMH also calls your method in a loop, but prevents the JIT compiler from optimizing it in this way. The quarter nanosecond per call is the price for this – and the smaller error. That is why it’s best to leave the repetition to JMH.
Test Data That Is Too Clean
If the test data is more uniform than the real data, the benchmark measures a case that doesn’t occur in the application. This section and the next one show this.
The class SortedDataBenchmark creates random numbers between 0 and 255 in its @Setup method and stores them in two arrays: once shuffled, as they were generated, and once sorted. Both benchmark methods iterate over one of these arrays and pass every number from 128 up to the Blackhole:
@Benchmark
public void sorted(Blackhole blackhole) {
consumeLargeValues(sorted, blackhole);
}
@Benchmark
public void shuffled(Blackhole blackhole) {
consumeLargeValues(shuffled, blackhole);
}
private void consumeLargeValues(int[] values, Blackhole blackhole) {
for (int value : values) {
if (value >= 128) {
blackhole.consume(value);
}
}
}
So both methods check the same numbers and pass the same numbers to the Blackhole. Nevertheless, the shuffled array is slower: With 1,024 elements, it takes 262 ns, the sorted one only 176 ns. With one million elements, the shuffled array takes 1.81 ms, almost ten times as long as the sorted one with 0.18 ms.
The reason is the branch prediction of the processor: For every condition, it guesses how it will turn out and continues working with the guessed branch before the result is known. Simply put, it remembers how the condition turned out last time and assumes that it will turn out the same way again. With sorted data, the condition value >= 128 switches from false to true only once, and the prediction is almost always right. With shuffled data, it is impossible to predict whether the next number is below 128 or not, and every wrong prediction costs time.
If the real data is unordered, a benchmark with sorted data therefore measures a considerably more favorable case. And with a small array, you would have greatly underestimated the difference.
Only One Type in the Test Data
The types of the test data can also be more uniform than in the application. The class SingleTypeBenchmark calls toString() on elements of an Object[] that contains only Integer, only Long, only Short, or a mix of all three types:
Benchmark Mode Cnt Score Error Units
SingleTypeBenchmark.mixedTypes avgt 15 6.344 ± 0.254 ns/op
SingleTypeBenchmark.onlyIntegers avgt 15 4.357 ± 0.022 ns/op
SingleTypeBenchmark.onlyLongs avgt 15 4.288 ± 0.021 ns/op
SingleTypeBenchmark.onlyShorts avgt 15 4.301 ± 0.026 ns/op
With only one type, a call takes 4.3 ns, with three mixed types 6.3 ns – 46% more than with, e.g., only Integer objects.
The difference is made by the call site of toString(): If only one type arrives there, the JIT compiler calls the toString() method directly on this type and builds its code into the benchmark method (inlining) – secured by a type check in case another type does arrive after all. With three types, this no longer works – then it generates a call that finds the matching method only at runtime based on the object type.
So a benchmark that only passes Integer objects measures the most favorable case – even if three types arrive at this point in the application.
By the way, array sizes that are powers of two can also distort the measurement: The article about 2D arrays shows how a size of 4,096 measures the cache instead of the code.
A Look at the Generated Code
How can JMH measure 4.66 ns for a call if the clock only ticks in steps of 41 ns? The answer is in the code that the annotation processor generates. For the first benchmark, it is in target/generated-sources/annotations, in the class IntToStringBenchmark_intToString_jmhTest. The measurement loop for the throughput:
result.startTime = System.nanoTime();
do {
blackhole.consume(l_inttostringbenchmark0_G.intToString());
operations++;
} while(!control.isDone);
result.stopTime = System.nanoTime();
You can see three things here:
- JMH takes the time only before and after the whole iteration, not around each call. An iteration takes ten seconds, around 240 million times as long as one step of the clock – so its inaccuracy doesn’t matter, not even if you shorten the iteration to one second. JMH then divides the measured time by the number of calls.
- JMH passes the return value of the benchmark method to
blackhole.consume()– that is why areturnis enough in your own code. You only need aBlackholeof your own if your benchmark calculates more than one value. - How long the loop runs is determined by the flag
control.isDone, which another thread sets when the iteration time has elapsed. Reading this flag is also part of the measured time – together with the rest of the loop, it is in the quarter nanosecond that, according to the baseline, a call through JMH costs.
Benchmarks with Multiple Threads
With @Threads(n), JMH calls a benchmark method simultaneously from n threads. JMH still measures the benchmark methods themselves one after the other, each with n threads. The annotation is placed on the benchmark method or, if it should apply to all methods, on the class.
On the command line, you override the number with -t – for all benchmarks of the run, even if different numbers are specified in the @Threads annotations. -t max uses as many threads as the machine has hardware threads.
The class ThreadsBenchmark lets four threads increment a counter – either all the same one or each its own:
@Threads(4)
public class ThreadsBenchmark {
@State(Scope.Benchmark)
public static class SharedCounter {
final AtomicLong value = new AtomicLong();
}
@State(Scope.Thread)
public static class OwnCounter {
final AtomicLong value = new AtomicLong();
}
@Benchmark
public long incrementShared(SharedCounter counter) {
return counter.value.incrementAndGet();
}
@Benchmark
public long incrementOwn(OwnCounter counter) {
return counter.value.incrementAndGet();
}
}
Which thread gets which counter is determined by the scope of the state class: SharedCounter with Scope.Benchmark exists once for all four threads, OwnCounter with Scope.Thread once per thread. The result:
Benchmark Mode Cnt Score Error Units
ThreadsBenchmark.incrementOwn avgt 15 1.642 ± 0.001 ns/op
ThreadsBenchmark.incrementShared avgt 15 23.136 ± 0.307 ns/op
With its own counter, a call takes 1.6 ns, with the shared one 23.1 ns – just over 14 times as long. With the shared counter, four processor cores write to the same cache line and have to take it away from each other on every write.
By the way, several threads count faster with a LongAdder. For this, ThreadsBenchmark has two more state classes, SharedAdder and OwnAdder, which contain a LongAdder instead of an AtomicLong, and two more benchmark methods, incrementSharedAdder() and incrementOwnAdder(), which count with them. The complete result:
Benchmark Mode Cnt Score Error Units
ThreadsBenchmark.incrementOwn avgt 15 1.642 ± 0.001 ns/op
ThreadsBenchmark.incrementOwnAdder avgt 15 4.387 ± 0.007 ns/op
ThreadsBenchmark.incrementShared avgt 15 23.136 ± 0.307 ns/op
ThreadsBenchmark.incrementSharedAdder avgt 15 4.476 ± 0.005 ns/op
If each thread has its own counter, the LongAdder is slower: A call takes 4.4 ns with its own LongAdder, only 1.6 ns with its own AtomicLong. If the threads share a counter, it is the other way around: The shared LongAdder takes 4.5 ns, the shared AtomicLong 23.1 ns – more than five times as long.
The reason: A LongAdder doesn’t count in a single field. As soon as several threads write to it at the same time, it creates a table of counter cells, and each thread usually writes to its own cell. The cells are in separate cache lines, so the cores don’t have to take them away from each other. In return, the increment() method doesn’t return a value, and only when sum() is called are all cells added up.
Groups with @Group
If different threads are to call different methods at the same time, e.g., reading and writing ones, you form a group. The class ReadWriteBenchmark lets three threads read a counter while a fourth one increments it:
@State(Scope.Group)
public class ReadWriteBenchmark {
private final AtomicLong counter = new AtomicLong();
@Benchmark
@Group("counter")
@GroupThreads(3)
public long read() {
return counter.get();
}
@Benchmark
@Group("counter")
@GroupThreads(1)
public long increment() {
return counter.incrementAndGet();
}
}
@Group combines the two methods into one benchmark, @GroupThreads determines how many threads call each method. Scope.Group ensures that all four threads access the same counter. JMH prints one value for the group and one each for the two methods:
Benchmark Mode Cnt Score Error Units
ReadWriteBenchmark.counter avgt 15 2.493 ± 0.047 ns/op
ReadWriteBenchmark.counter:increment avgt 15 4.782 ± 0.075 ns/op
ReadWriteBenchmark.counter:read avgt 15 1.730 ± 0.067 ns/op
A read access takes 1.7 ns, an increment 4.8 ns. The value for the group, 2.5 ns, is the mean over all four threads: three times 1.7 ns and once 4.8 ns. With three threads reading at the same time, the increment costs almost three times as much as with its own counter in the previous example (1.6 ns), but only around a fifth of what four writing threads need on a shared counter (23.1 ns).
Pitfalls with Multiple Threads
Keep two things in mind when benchmarking with multiple threads.
If a benchmark method starts asynchronous work, e.g., with a CompletableFuture, JMH only measures the start. To measure the asynchronous work, the method must wait for its result before it returns.
And if two threads write to adjacent fields of the same state object, the benchmark mainly measures how the processor cores pass the shared cache line back and forth (false sharing).
Profilers: Why the Number Is What It Is
A benchmark tells you how fast a piece of code is. The profilers that come with JMH show why it is that fast. With -lprof, JMH lists them, separated into those you can use on the current machine and those that are not available there. The following table shows a selection:
| Profiler | What it shows | Runs on |
|---|---|---|
gc | allocated bytes per call, number and duration of GC runs | all platforms |
stack | in which methods the threads are, by sampling | all platforms |
jfr | records the benchmark with the Java Flight Recorder | all platforms |
comp | time the JIT compiler needed | all platforms |
async | CPU and allocation profiles with async-profiler | Linux, macOS; needs the async-profiler library |
perfasm, perfnorm | the hottest machine code or hardware counters per call | Linux with perf |
dtraceasm | the hottest machine code | macOS, with root privileges |
xperfasm | the hottest machine code | Windows with xperf |
The profilers for the machine code additionally need the library hsdis so that the JVM can disassemble its machine code.
You will need -prof gc most often. For the first benchmark, with one fork:
java -jar target/benchmarks.jar 'eu\.happycoders\.jmh\.IntToStringBenchmark' -prof gc -f 1
JMH then prints four additional lines below the result:
Benchmark Mode Cnt Score Error Units
IntToStringBenchmark.intToString thrpt 5 216185066.797 ± 1519588.438 ops/s
IntToStringBenchmark.intToString:gc.alloc.rate thrpt 5 9896.036 ± 69.505 MB/sec
IntToStringBenchmark.intToString:gc.alloc.rate.norm thrpt 5 48.000 ± 0.001 B/op
IntToStringBenchmark.intToString:gc.count thrpt 5 1049.000 counts
IntToStringBenchmark.intToString:gc.time thrpt 5 467.000 ms
gc.alloc.rate is the allocation rate: just under 9,900 MB per second, averaged over the five measurement iterations. gc.count and gc.time are the number of GC runs and their total duration, summed over all measurement iterations – that is why there is no error there. In 50 seconds of measurement time, the garbage collector cleaned up 1,049 times and needed 467 ms for this, just under 1% of the time.
The line gc.alloc.rate.norm gives the allocated bytes per call: 48. This number doesn’t depend on how fast the machine is, and it changes as soon as the JIT compiler optimizes an allocation away. That is how the section Dead Code Elimination showed that the discarded Integer.toString() allocates only 24 bytes. The article How to Convert String to int uses the same line to show how escape analysis removes the allocation of an Integer object.
-prof stack shows without any further tools in which methods the time is spent. -prof jfr records the benchmark with the Java Flight Recorder, so that you can analyze it, e.g., with JDK Mission Control.
You will need the other profilers in the table less often: comp if you want to know how long the JIT compiler worked; async for more precise CPU and allocation profiles than stack provides; and the profilers for the machine code if you want to see what the JIT compiler has made of your code.
Running Benchmarks and Keeping the Results
If a project contains several benchmarks, you can select specifically which of them JMH measures. You can also adjust the settings for a single run and keep the results in such a way that you can later compare them with another JDK or on another machine. The following four sections show how.
Selecting Benchmarks
With the argument after benchmarks.jar, you can specify which benchmarks JMH starts; without an argument, JMH starts all of them. The argument is a regular expression that JMH compares with the full name of each benchmark method – package, class, and method. It only has to match part of the name. With -l, you can see which benchmarks it would select, without starting them:
java -jar target/benchmarks.jar 'eu\.happycoders\.jmh\.DeadCodeBenchmark\.log' -l
A short expression like Benchmark matches every benchmark method whose full name contains this text – including those in other packages or classes. That is why I always write the expression with the package.
With -e, you additionally exclude benchmarks whose name matches a second expression: 'eu\.happycoders\.jmh\.DeadCodeBenchmark' -e 'log' selects the three intToString variants of DeadCodeBenchmark, but not the three log variants.
Annotation or Command Line
Every setting you make via annotation can be overridden on the command line. Besides the options from the section Forks, Warm-up, and Iterations, these include:
-bmfor the mode, e.g.,-bm avgtor-bm thrpt,-tufor the time unit, e.g.,-tu nsor-tu ms,-tfor the threads, e.g.,-t 4or-t max,-jvmArgsfor the JVM options, e.g.,-jvmArgs "-Xms2g -Xmx2g".
The command line takes precedence: If a benchmark is annotated with @Fork(3), for example, but started with -f 1, only one fork is created.
Saving Results
By default, JMH prints the results only to the console. With -rf json, it also writes them to a file in JSON format; with -rff, you specify the file name:
java -jar target/benchmarks.jar 'eu\.happycoders\.jmh\.IntToStringBenchmark' \
-rf json -rff results/first-benchmark.json
Without -rff, the file is called jmh-result.json. Besides JSON, JMH knows the formats CSV, SCSV, text, and LaTeX. If you only specify a file name with -rff, but no format, JMH writes the results in CSV format – even if the name ends in .json.
Besides the mean and the error, the JSON file contains the values of every single measurement iteration from every fork. On the console, these values appear only during the run; the result table at the end shows only mean and error.
With -o, JMH writes the console output to a file instead – nothing appears on the console anymore.
You can visualize the JSON files, e.g., with the JMH Visualizer, which the JMH README lists among the community projects.
Multiple JDKs, Multiple Machines
The benchmarks.jar contains everything it needs to run the benchmarks. If you start it with the java command of another JDK, it measures with that JDK’s Java version – that is how the measurement series across Java 8 to 27 in the article How to Convert int to String came about.
Alternatively, you start JMH with your default JDK and use -jvm to specify the java command with which JMH starts the forks:
java -jar target/benchmarks.jar 'eu\.happycoders\.jmh\.IntToStringBenchmark' \
-jvm ~/.sdkman/candidates/java/25.0.2-open/bin/java
JMH itself then runs with the JDK from the PATH, but the measurement runs under Java 25.
Likewise, you can copy the benchmarks.jar to a second machine and start it there.
Numbers You Can Rely On
A correctly written benchmark alone doesn’t yet deliver comparable numbers. The environment in which it runs also matters.
The machine. Nothing else should run during the measurement – no IDE that is indexing, no backup, and no browser that is doing something in some tab without you noticing. A laptop must measure on mains power, because in battery mode the operating system may throttle the processor. If the JVM runs in a VM or under WSL2, it shares the cores with the host system; only measure there what is also supposed to run there.
The JVM. By default, the JVM chooses the heap size and the garbage collector based on the memory and the number of cores of the machine. If you want to compare two machines, you have to set both in @Fork(jvmArgsAppend = …), e.g., with -Xms4g -Xmx4g -XX:+UseG1GC. Then both run with the same configuration.
The day of measurement. The same benchmark on the same machine with the same JDK doesn’t produce the same number on two different days. In the measurements for the article How to Convert int to String, the level shifted by up to six percent between two days. Therefore, only compare numbers from one measurement campaign, and alternate the order of the variants so that a drift affects all of them equally.
The details of a number. Every number you pass on should come with the machine, JDK build, JMH version, number of forks and iterations, and the date. The “Measurement” boxes in the articles on this website are an example.
The build. Benchmarks are only of limited use as a check in a CI pipeline. Shared CI runners share the hardware with other jobs, and their numbers can fluctuate more than the difference that the build is supposed to detect as a real regression. If you run benchmarks automatically, then do so on a dedicated machine that does nothing else.
Common Mistakes
Most mistakes that developers make when benchmarking go unnoticed: The benchmark delivers a number that looks plausible – and is wrong nonetheless. The following list summarizes the most common mistakes, together with what you should do instead:
- Measuring with a stopwatch around a loop: The measurement includes interpreter, JIT compiler, and garbage collector; the results fluctuate strongly from run to run. Use JMH.
- Not using the result of an operation: The JIT compiler removes the calculation completely or partially, and you measure less than you wanted to measure. Return the result with
returnor pass it to aBlackhole. - Using a constant as input: If the input is already fixed at compile time, the JIT compiler can precompute the call completely or partially, and the benchmark only measures the rest. Read the input from a non-final field of a state object.
- Not measuring a baseline: Without a comparison with an empty method, you don’t notice when the code to be measured has been optimized away and the benchmark only measures the call through JMH. Measure a baseline as well.
- Writing your own loop: The JIT compiler may combine iterations, and you then mainly measure the loop. Leave the repetition to JMH, and where a loop is necessary, specify the number in
@OperationsPerInvocation. - Starting benchmarks from a JUnit test: The forks inherit the options of the test JVM including agents such as JaCoCo, and the benchmark runs with every test run – and measures these agents too. Put the benchmarks into a separate project.
- Using
@Setup(Level.Invocation)for a call of nanoseconds: The timestamps around each call cost more than the call itself. Prepare test data that doesn’t change withLevel.Trial; if the benchmark changes the data, useLevel.Iterationwith a fixed batch size. - Measuring with only one fork or with
@Fork(0): One fork doesn’t show how much the next JVM deviates; without a fork, the benchmark runs in JMH’s own JVM. Measure with at least three forks. - Comparing numbers from two days or two machines: The level can shift by several percent between two days. Only compare numbers from one measurement campaign.
- Measuring in the IDE: The IDE runs on the same cores and compiles or indexes in the background. Start the
benchmarks.jarfrom the command line. - Reading a difference within the error interval as a result: If the error intervals of two results overlap, no difference is proven. Then don’t claim one.
Summary
A measurement with System.nanoTime() around a loop is not a good benchmark. It also measures the warm-up phase, the garbage collector, and the order. In my runs, of two methods executing the same code, the one measured first was slower every time. And a loop whose result was not used ran more than ten times as fast as with the result used.
JMH measures in separate JVMs (forks), after a warm-up phase and in several iterations, and prints a mean with an error interval.
Even JMH doesn’t stop the JIT compiler. Return every result or pass it to a Blackhole, read every input from a non-final field, and measure a baseline as well: A benchmark that is as fast as an empty method has optimized away the code to be measured and only measures the call through JMH.
Avoid test data that is more uniform than the real data. A method call on sorted data ran almost ten times as fast with one million elements as the same method call on unsorted data.
For every new benchmark, I recommend:
- measure a baseline as well,
- check the allocations with
-prof gc, - measure with at least three forks,
- record the result with machine, JDK, and date.
You can use the benchmarks in this article as a template for this – they are in the GitHub repository java-jmh.
If this article has helped you, I would greatly appreciate a positive review on my ProvenExpert profile. Your feedback helps me improve my content and motivates me to write new informative articles.




