Java Microbenchmarking with JMH
A loop with System.nanoTime around it measures the JIT, the warm-up and the garbage collector as much as your code. JMH, the OpenJDK benchmark harness, handles warm-up, forks and result statistics for you. Every benchmark on this page was run with JMH 1.37 on JDK 25, and the tables are the real results, including the mistakes JMH cannot catch for you.
Contents
Introduction How the JVM runs a method: interpreter, C1 and C2 What JMH does for you Where JMH helps, and where it does not Setup and the JDK 23 annotation processing change Dead code: a result nobody uses can disappear Constant folding: measuring a value computed at compile time @State and @Param: inputs and a size matrix @Setup levels: when the input changes under you Benchmark modes Four more mistakes, measured Checklist
Introduction
JMH, the Java Microbenchmark Harness, is a tool for measuring how fast a small piece of Java code runs: one method, one data structure operation, or two ways of doing the same job side by side. You write each piece as a method marked @Benchmark
JMH is a development tool, used the way you use a test framework. Benchmarks live in their own project or module, you run them on your machine or a test server, and they never ship with the application. JMH does not make your code faster. It tells you which version is faster and by how much, and you then make the change in your own code.
JMH comes from the people who build the JVM. Aleksey Shipilëv of Oracle's Java SE performance team
Why not just call System.nanoTime()
How the JVM runs a method: interpreter, C1 and C2
When a program starts, the JVM runs each method in the interpreter, which reads the bytecode one instruction at a time. That needs no preparation, but it is slow. While it runs, the JVM counts how often each method is called and how many times its loops go round. Once a method gets hot (runs often enough), the JVM hands it to a JIT (just-in-time) compiler, which turns it into machine code in the background while the program keeps running.
HotSpot, the JVM in OpenJDK, has two JIT compilers, C1 and C2, and uses them in steps called tiers:
- Tier 0, the interpreter: where every method starts.
- Tier 3, C1 with profiling: C1 compiles quickly and produces reasonably fast code. At tier 3 it also adds counters that record how the method behaves, such as which branches are taken and which classes reach each call. This record is called the profile.
- Tier 4, C2: C2 compiles slowly but produces much faster code. It uses the profile to optimize aggressively. It inlines small methods into their callers, removes code whose result is never used, and computes values once when they cannot change.
Tiers 1 and 2 are side routes, also compiled by C1. Tier 1 is C1 with no profiling, for trivial methods such as a getter that only returns a field. C2 is unlikely to make those any faster, so the JVM compiles them once at tier 1 and leaves them there. Tier 2 is C1 with light profiling, which counts calls and loop turns but not branches or classes. The JVM uses it when C2 has a long queue of work, and moves the method on to tier 3 once C2 catches up. The flag -XX:TieredStopAtLevel=1
If something C2 assumed stops being true, for example a call that had only ever seen one class now receives another, the JVM throws that machine code away and the method goes back to the interpreter until it is compiled again. This is the dashed arrow in the picture, and it is called deoptimization.
Here is what that looks like from the outside. This program times one method the way many people first try it. It calls countAboveFifty
package demo;
// Times the same method in rounds with System.nanoTime, the way many people first try it
public class NaiveTiming {
static int[] data = new java.util.Random(1).ints(1000, 0, 100).toArray();
static int countAboveFifty(int[] values) {
int count = 0;
for (int v : values) {
if (v > 50) {
count++;
}
}
return count;
}
public static void main(String[] args) {
long sink = 0; // keep the results in use
for (int round = 1; round <= 12; round++) {
long start = System.nanoTime();
for (int i = 0; i < 2000; i++) {
sink += countAboveFifty(data);
}
long perCall = (System.nanoTime() - start) / 2000;
System.out.println("round " + round + ": " + perCall + " ns per call");
}
System.out.println("(sink " + sink + ")");
}
}
Running it prints:
round 1: 7617 ns per call
round 2: 777 ns per call
round 3: 774 ns per call
round 4: 768 ns per call
round 5: 758 ns per call
round 6: 760 ns per call
round 7: 744 ns per call
round 8: 741 ns per call
round 9: 742 ns per call
round 10: 738 ns per call
round 11: 762 ns per call
round 12: 753 ns per call
(sink 12264000)
The first round took 7,617 ns per call, and every later round about 750 ns. The code never changed, but the way it ran did. Running the same program with -XX:+PrintCompilationcountAboveFifty
36 46 % 3 demo.NaiveTiming::countAboveFifty @ 10 (40 bytes)
36 47 3 demo.NaiveTiming::countAboveFifty (40 bytes)
36 48 % 4 demo.NaiveTiming::countAboveFifty @ 10 (40 bytes)
40 46 % 3 demo.NaiveTiming::countAboveFifty @ 10 (40 bytes) made not entrant: OSR invalidation of lower level
41 49 4 demo.NaiveTiming::countAboveFifty (40 bytes)
44 47 3 demo.NaiveTiming::countAboveFifty (40 bytes) made not entrant: not used
The first column is the time in milliseconds since the JVM started, and the number just before the method name is the tier. Within 5 milliseconds, all inside the first round, the method went from the interpreter to C1 at tier 3 and then to C2 at tier 4. The %countAboveFifty-Xint
So the first round mixed interpreter, C1 and C2 time, and a short timing loop can report any of them. That is only the first trap. C2 can also delete the work you meant to measure, or compute it once ahead of time, and the profile built for one piece of code can change how the next one is compiled.
What JMH does for you
When you run a benchmark, JMH takes care of the parts that a hand-written timing loop gets wrong:
- Warm-up: it runs warm-up iterations first and leaves them out of the score, so the score comes from compiled code.
- Forks: it runs each benchmark in a fresh JVM, so the profile built for one benchmark cannot change how the next one is compiled.
- The measurement loop: it generates the loop that calls your method, and passes every return value to a
, an object that keeps the JIT from treating the result as unused.Blackhole - Statistics: it repeats the measurement and reports the score with an error range.
- Profilers: with options such as
, it adds numbers such as the bytes allocated per call.-prof gc
What it cannot check is whether your benchmark measures what you meant. Its own README warns that no harness will "magically free you from considering benchmarking pitfalls", and a benchmark that runs under JMH can still measure the wrong thing.
Where JMH helps, and where it does not
JMH is the right tool when the question is about a small piece of code on its own:
- Comparing two ways of doing the same thing, such as
against+ , orStringBuilder againstHashMap .TreeMap - Finding the cost of a library call or a data structure at the sizes your program really uses.
- Checking whether a hot method got faster or slower after a code change, a JDK upgrade or a new JVM flag.
- Finding allocation that the time alone hides, with
.-prof gc
It is the wrong tool for measuring a whole application, a service's response times or its startup. There, many things run at once, and a method may be inlined or compiled differently than in a small benchmark. Use a load test for those numbers, and a profiler such as
Setup and the JDK 23 annotation processing change
The quickest way to start is the project template (a Maven archetype) that the JMH README recommends:
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample \
-DartifactId=test \
-Dversion=1.0
It creates a project in a testMyBenchmarkmvn clean verifytarget/benchmarks.jarjava -jar target/benchmarks.jarpom.xmlprovidedMyBenchmarkMETA-INF/BenchmarkList
JMH has two parts: jmh-corejmh-generator-annprocess@Benchmark
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.37</version>
</dependency>
<!-- in maven-compiler-plugin's <configuration> -->
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.37</version>
</path>
</annotationProcessorPaths>
Many older guides put the processor on the normal classpath with provided
| JDK | javac result | Running the benchmark |
|---|---|---|
| 21 | A note that "A future release of javac may disable annotation processing", and META-INF/BenchmarkList | Works |
| 25 | No message, and nothing is generated | RuntimeException: ERROR: Unable to find the resource: /META-INF/BenchmarkList |
The fix is annotationProcessorPaths-proc:full
In Gradle, the processor belongs on the annotationProcessorimplementationannotationProcessorMETA-INF/BenchmarkList
// build.gradle.kts
dependencies {
implementation("org.openjdk.jmh:jmh-core:1.37")
annotationProcessor("org.openjdk.jmh:jmh-generator-annprocess:1.37")
}
The examples on this page start JMH from a mainbenchmarks.jar
package bench;
import java.util.Collection;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.results.format.ResultFormatFactory;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.ChainedOptionsBuilder;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import org.openjdk.jmh.runner.options.VerboseMode;
// Runs every @Benchmark in one class and prints JMH's own summary table
final class Bench {
private Bench() {
}
// The settings used on this page; a program can change any of them before running
static ChainedOptionsBuilder options(Class<?> benchmarkClass) {
return new OptionsBuilder()
.include("^" + benchmarkClass.getName() + "\\.") // regex on method names
.forks(1) // 1 fresh JVM per benchmark
.warmupIterations(3)
.warmupTime(TimeValue.milliseconds(300))
.measurementIterations(10)
.measurementTime(TimeValue.milliseconds(500))
.jvmArgsAppend("--sun-misc-unsafe-memory-access=allow") // JDK 24+ warning
.verbosity(VerboseMode.SILENT); // skip the per-iteration log
}
static Collection<RunResult> run(ChainedOptionsBuilder options) throws Exception {
Collection<RunResult> results = new Runner(options.build()).run();
ResultFormatFactory.getInstance(ResultFormatType.TEXT, System.out).writeOut(results);
return results;
}
static void run(Class<?> benchmarkClass) throws Exception {
run(options(benchmarkClass));
}
}
runs each benchmark in a fresh JVM, so the JIT decisions made for one benchmark do not affect the next. JMH's default is 5 forks; 1 keeps this page quick.forks(1)- 3 warm-up iterations of 0.3 seconds and 10 measured iterations of 0.5 seconds are far shorter than JMH's defaults: 5 forks, each with 5 warm-up and 5 measured iterations of 10 seconds. They are enough to show the effects below, but use the defaults or longer for numbers you will act on.
- JDK 24 and later print a warning when a library calls the memory methods of
(JEP 498), and JMH 1.37 does. Each forked JVM printed four lines of it. A fork inherits the JVM options of the program that starts it, so starting the programs withsun.misc.Unsafe , as here, is enough. The helper also passes it to the forks, so the warning stays away when a program is started without it.--sun-misc-unsafe-memory-access=allow
The tables are from a 2-CPU cloud machine. Absolute numbers will differ on yours; the ratios between rows are the point. "Error" is half the width of JMH's 99.9% confidence interval, which it computes from the measured iterations and which assumes they are normally distributed. With one fork it covers only the noise inside that one JVM, not how much a second JVM run would differ, so use several forks before trusting a small difference.
Dead code: a result nobody uses can disappear
The JIT removes code whose result is never used. A benchmark that computes something and throws it away may end up measuring nothing. The test uses Math.logx
package bench;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
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.infra.Blackhole;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class DeadCode {
double x = Math.PI; // a field, so the JIT cannot treat it as a constant
@Benchmark
public void baseline() {
// empty: the cost of the benchmark call itself
}
@Benchmark
public void discarded() {
Math.log(x); // result unused, so the JIT may delete the call
}
@Benchmark
public double returned() {
return Math.log(x); // JMH consumes return values for you
}
@Benchmark
public void blackhole(Blackhole bh) {
bh.consume(Math.log(x)); // explicit sink, for methods with several results
}
public static void main(String[] args) throws Exception {
Bench.run(DeadCode.class);
}
}
Output:
Benchmark Mode Cnt Score Error Units
DeadCode.baseline avgt 10 0.273 ± 0.017 ns/op
DeadCode.blackhole avgt 10 5.162 ± 0.185 ns/op
DeadCode.discarded avgt 10 0.273 ± 0.016 ns/op
DeadCode.returned avgt 10 5.440 ± 0.900 ns/op
discardedbaselineMath.logBlackhole.consumediscarded
The run header (hidden here by the silent mode) said Blackhole mode: compiler (auto-detected, use -Djmh.blackhole.autoDetect=false to disable)Blackhole.consume-XX:CompileCommand=blackhole
Constant folding: measuring a value computed at compile time
A common first benchmark compares "Hello, " + "World" + "!"StringBuilder+@State
package bench;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ConstantFolding {
String greeting = "Hello, ";
String name = "World";
@Benchmark
public String literals() {
return "Hello, " + "World" + "!"; // javac joins these into one constant
}
@Benchmark
public String plusOnFields() {
return greeting + name + "!"; // real concatenation at run time
}
@Benchmark
public String builderOnFields() {
return new StringBuilder().append(greeting).append(name).append('!').toString();
}
public static void main(String[] args) throws Exception {
Bench.run(ConstantFolding.class);
}
}
Output:
Benchmark Mode Cnt Score Error Units
ConstantFolding.builderOnFields avgt 10 13.057 ± 1.880 ns/op
ConstantFolding.literals avgt 10 0.301 ± 0.046 ns/op
ConstantFolding.plusOnFields avgt 10 13.181 ± 2.428 ns/op
literalsbaseline+StringBuilder+invokedynamic+
@State and @Param: inputs and a size matrix
@State@ParamHashMapTreeMap
package bench;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
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;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MapLookup {
@Param({"1024", "65536", "1048576"}) // powers of two, so "& mask" picks an index
int size;
Map<Integer, Integer> hash;
Map<Integer, Integer> tree;
Integer[] keys; // looked up in a shuffled order
int next;
@Setup(Level.Trial) // once per fork, outside the timing
public void fill() {
hash = new HashMap<>();
tree = new TreeMap<>();
keys = new Integer[size];
Random random = new Random(42);
for (int i = 0; i < size; i++) {
hash.put(i, i);
tree.put(i, i);
keys[i] = i;
}
for (int i = size - 1; i > 0; i--) { // Fisher-Yates shuffle
int j = random.nextInt(i + 1);
Integer t = keys[i];
keys[i] = keys[j];
keys[j] = t;
}
}
@Benchmark
public Integer hashMapGet() {
return hash.get(keys[next++ & (size - 1)]);
}
@Benchmark
public Integer treeMapGet() {
return tree.get(keys[next++ & (size - 1)]);
}
public static void main(String[] args) throws Exception {
Bench.run(MapLookup.class);
}
}
Output:
Benchmark (size) Mode Cnt Score Error Units
MapLookup.hashMapGet 1024 avgt 10 3.495 ± 0.643 ns/op
MapLookup.hashMapGet 65536 avgt 10 34.068 ± 8.437 ns/op
MapLookup.hashMapGet 1048576 avgt 10 56.856 ± 10.552 ns/op
MapLookup.treeMapGet 1024 avgt 10 39.113 ± 3.109 ns/op
MapLookup.treeMapGet 65536 avgt 10 285.304 ± 58.164 ns/op
MapLookup.treeMapGet 1048576 avgt 10 1000.745 ± 106.221 ns/op
Reading the table:
is called O(1), yet it got much slower from 1,024 to 1,048,576 entries. The number of steps did not change; the memory did. A million entries do not fit in the CPU cache, so most lookups wait for main memory, both for the boxedHashMap.get key and for the map's own table and node.Integer does about log2(n) comparisons: 10 at 1,024 entries and 20 at 1,048,576. It grew far more than 2 times because each step down the tree is another likely cache miss.TreeMap.get- JMH crosses all
values, so 2 methods and 3 sizes gave 6 rows. Two@Param fields with 4 and 3 values would give 12 runs per method, which adds up quickly.@Param
| Scope | Instances | Use for |
|---|---|---|
Scope.Thread | One per benchmark thread | Mutable state such as counters; the usual choice when unsure |
Scope.Benchmark | One shared by all threads of a benchmark, within one fork | Shared data, or measuring contention on it |
Scope.Group | One per thread group (@Group | Producer and consumer benchmarks |
@StateMapLookupScope.BenchmarkScope.Thread
@Setup levels: when the input changes under you
Sorting is a good test because sorting changes its own input. After the first call, the array is sorted, and every later call sorts data that is already in order. The array has 200,000 elements so that one sort takes more than a millisecond, the minimum the JMH documentation gives for per-call setup (explained below).
package bench;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class SortSetup {
static final int N = 200000;
static int[] randomData() {
return new Random(7).ints(N).toArray();
}
// Wrong: filled once, so every call after the first sorts an already sorted array
@State(Scope.Thread)
public static class FilledOnce {
int[] data;
@Setup(Level.Trial)
public void fill() {
data = randomData();
}
}
// Right: a fresh unsorted copy before each call, not counted in the time
@State(Scope.Thread)
public static class FilledEachCall {
final int[] source = randomData();
int[] data;
@Setup(Level.Invocation)
public void fill() {
data = source.clone();
}
}
@Benchmark
public int[] sortFilledOnce(FilledOnce s) {
Arrays.sort(s.data);
return s.data;
}
@Benchmark
public int[] sortFilledEachCall(FilledEachCall s) {
Arrays.sort(s.data);
return s.data;
}
@Benchmark
public int[] cloneThenSort(FilledEachCall s) {
int[] copy = s.source.clone(); // the copy is now part of the measured time
Arrays.sort(copy);
return copy;
}
public static void main(String[] args) throws Exception {
Bench.run(SortSetup.class);
}
}
Output:
Benchmark Mode Cnt Score Error Units
SortSetup.cloneThenSort avgt 10 1520.828 ± 66.119 us/op
SortSetup.sortFilledEachCall avgt 10 1389.399 ± 159.543 us/op
SortSetup.sortFilledOnce avgt 10 37.935 ± 7.538 us/op
| Benchmark | Setup | What was timed |
|---|---|---|
sortFilledOnce | Level.Trial | Sorting an already sorted array, for all but the first call |
sortFilledEachCall | Level.Invocation | Sorting random data, the intended measurement |
cloneThenSort | Copy inside the benchmark | Copying 200,000 ints plus the sort |
sortFilledOnceArrays.sorttryMergeRunsDualPivotQuicksortLevel.InvocationcloneThenSort
The LevelLevel.Iteration
| Level | Runs |
|---|---|
Level.Trial | Once per fork, before warm-up (the default) |
Level.Iteration | Before or after each warm-up and measurement iteration |
Level.Invocation | Around every single call of the benchmark method |
Benchmark modes
| Mode | Score | Answers |
|---|---|---|
Mode.Throughput | Operations per time unit | How many calls per second can this sustain? |
Mode.AverageTime | Time per operation | What does one call cost on average? (used on this page) |
Mode.SampleTime | Sampled call times with percentiles | What do p50, p99 and the worst calls look like? |
Mode.SingleShotTime | Time of one call, without warm-up iterations by default | What does a cold call cost, such as start-up code? |
Mode.All | All of the above | Exploring |
For a single thread, average time and throughput are the same measurement inverted. Pick the one that reads naturally for the question, and use SampleTime
Four more mistakes, measured
Each program below uses the same helper and settings as the rest of the page, unless its main
A loop of your own inside the benchmark
Writing a loop to "amplify" a tiny operation looks harmless. Here one addition is measured directly and inside a 1,000-step loop, with @OperationsPerInvocation
package bench;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class LoopInside {
int x = 1;
int y = 2;
@Benchmark
public int once() {
return x + y; // one addition per call
}
@Benchmark
@OperationsPerInvocation(1000) // JMH divides the time by 1,000
public int loop1000() {
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += x + y; // the same addition, in our own loop
}
return sum;
}
public static void main(String[] args) throws Exception {
Bench.run(LoopInside.class);
}
}
Output:
Benchmark Mode Cnt Score Error Units
LoopInside.loop1000 avgt 10 0.028 ± 0.002 ns/op
LoopInside.once avgt 10 0.732 ± 0.030 ns/op
The loop version claims each addition costs 0.028 ns, about 26 times less than the 0.732 ns of the direct call and less than one cycle of the CPU's rated 2.1 GHz. The JIT is free to compute x + y
forks(0): the score depends on what ran before
With forks(0)c.next()
package bench;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class ForkOrder {
interface Counter {
int next();
}
// Three classes with identical code: only the type differs
static final class First implements Counter {
int n;
public int next() {
return n++;
}
}
static final class Second implements Counter {
int n;
public int next() {
return n++;
}
}
static final class Third implements Counter {
int n;
public int next() {
return n++;
}
}
Counter first = new First();
Counter second = new Second();
Counter third = new Third();
// One shared method: the JIT's profile of c.next() records every type it has seen
static int sum(Counter c) {
int s = 0;
for (int i = 0; i < 10000; i++) {
s += c.next();
}
return s;
}
@Benchmark
public int a_first() { // JMH runs benchmarks in name order
return sum(first);
}
@Benchmark
public int b_second() {
return sum(second);
}
@Benchmark
public int c_third() {
return sum(third);
}
public static void main(String[] args) throws Exception {
System.out.println("forks(0): all three in this JVM, one after another");
Bench.run(Bench.options(ForkOrder.class).forks(0));
System.out.println();
System.out.println("forks(1): each benchmark in a fresh JVM");
Bench.run(ForkOrder.class);
}
}
Output:
forks(0): all three in this JVM, one after another
Benchmark Mode Cnt Score Error Units
ForkOrder.a_first avgt 10 3.553 ± 0.051 us/op
ForkOrder.b_second avgt 10 3.521 ± 0.018 us/op
ForkOrder.c_third avgt 10 28.155 ± 9.104 us/op
forks(1): each benchmark in a fresh JVM
Benchmark Mode Cnt Score Error Units
ForkOrder.a_first avgt 10 3.520 ± 0.030 us/op
ForkOrder.b_second avgt 10 3.585 ± 0.097 us/op
ForkOrder.c_third avgt 10 3.552 ± 0.071 us/op
In one JVM, the third benchmark scored 28.155 us/op against about 3.5 for the first two, only because it ran third. Running it again with -XX:+PrintInliningnextCounter::nextforks(1)
No warm-up
This program sets warmupIterations(0)
package bench;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
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.results.IterationResult;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.options.TimeValue;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class NoWarmUp {
List<String> words = List.of("alpha", "beta", "gamma", "delta", "epsilon",
"zeta", "eta", "theta", "iota", "kappa");
@Benchmark
public String joinUpper() {
return String.join(",", words.stream()
.filter(w -> w.length() > 3)
.map(String::toUpperCase)
.toList());
}
public static void main(String[] args) throws Exception {
RunResult result = Bench.run(Bench.options(NoWarmUp.class)
.warmupIterations(0) // the mistake
.measurementIterations(8)
.measurementTime(TimeValue.milliseconds(100)))
.iterator().next();
int i = 1;
for (IterationResult it : result.getBenchmarkResults().iterator().next()
.getIterationResults()) {
System.out.printf("iteration %d: %.3f us/op%n", i++, it.getPrimaryResult().getScore());
}
}
}
Output:
Benchmark Mode Cnt Score Error Units
NoWarmUp.joinUpper avgt 8 1.000 ± 2.563 us/op
iteration 1: 4.298 us/op
iteration 2: 0.758 us/op
iteration 3: 0.600 us/op
iteration 4: 0.460 us/op
iteration 5: 0.663 us/op
iteration 6: 0.307 us/op
iteration 7: 0.401 us/op
iteration 8: 0.511 us/op
The first iteration took 4.298 us/op, most likely because the code was still interpreted or compiled at a lower tier, and later iterations fell to between 0.307 and 0.758. Averaged in, that one cold iteration pushed the score to 1.000, with an error of 2.563 that is larger than the score itself. A huge error next to a small score is a hint that the warm-up was too short.
Time looks fine, allocation does not: -prof gc
Escape analysis lets the JIT remove an object that never leaves the compiled code. If the object is passed to a method that is not inlined, it escapes and the allocation stays. Small benchmarks are inlined easily; in a larger application the same call may not be. The gc-prof gc
package bench;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
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.profile.GCProfiler;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class HiddenAllocation {
record Point(double x, double y) {
}
double x = 3;
double y = 4;
static double length(Point p) {
return Math.sqrt(p.x() * p.x() + p.y() * p.y());
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE) // as if the method were too big
static double lengthNotInlined(Point p) {
return Math.sqrt(p.x() * p.x() + p.y() * p.y());
}
@Benchmark
public double inlined() {
return length(new Point(x, y));
}
@Benchmark
public double notInlined() {
return lengthNotInlined(new Point(x, y));
}
public static void main(String[] args) throws Exception {
Bench.run(Bench.options(HiddenAllocation.class)
.addProfiler(GCProfiler.class)); // same as -prof gc
}
}
Output:
Benchmark Mode Cnt Score Error Units
HiddenAllocation.inlined avgt 10 2.147 ± 0.039 ns/op
HiddenAllocation.inlined:gc.alloc.rate avgt 10 0.013 ± 0.001 MB/sec
HiddenAllocation.inlined:gc.alloc.rate.norm avgt 10 ≈ 10⁻⁵ B/op
HiddenAllocation.inlined:gc.count avgt 10 ≈ 0 counts
HiddenAllocation.notInlined avgt 10 6.621 ± 0.289 ns/op
HiddenAllocation.notInlined:gc.alloc.rate avgt 10 4605.830 ± 200.120 MB/sec
HiddenAllocation.notInlined:gc.alloc.rate.norm avgt 10 32.000 ± 0.001 B/op
HiddenAllocation.notInlined:gc.count avgt 10 84.000 counts
HiddenAllocation.notInlined:gc.time avgt 10 99.000 ms
The number to read is gc.alloc.rate.normlengthPointgc.count-lprofgcstackcompjfrperfasmperf
Checklist
- Return every result or pass it to a
, and include an empty baseline so a deleted computation stands out.Blackhole - Read inputs from
fields, never from literals or@State constants the compiler can fold.static final - Check that the input is the same on every call; operations that change their input need
orLevel.Invocation setup.Level.Iteration - Use realistic sizes and access patterns. The
results changed far more with size than any O() estimate suggests.HashMap - Look at the error column. When two error ranges overlap, the benchmark has not shown a difference, and an error larger than the score points to too little warm-up.
- Do not write your own loop around the operation, and never use
for numbers you will act on.forks(0) - Run
when allocation matters, because time alone can hide it.-prof gc - Run with several forks and the default iteration times before drawing conclusions, and on hardware like production.
For finding where time goes in a running application, rather than comparing two snippets, use a profiler; see the