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.

CsCode.ioUpdated
Share

Contents

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, and JMH runs it the way the JVM runs code in a long-lived program, after warm-up and in fresh JVMs. It then reports a score with an error range, so you can tell a real difference from noise.

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 proposed it for OpenJDK in February 2013, based on a harness the team had built for internal use in 2011, and version 1.0 followed in 2014. It now lives in OpenJDK's Code Tools project, and the JDK uses it for its own performance tests. Since JDK 12, the JDK source code includes a suite of JMH benchmarks (JEP 230).

Why not just call System.nanoTime() before and after a loop? Because at first, the code you time is not the code that runs for the rest of the program's life. The reason is in how the JVM runs a method.

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:

A method starts in the interpreter at tier 0, is compiled by C1 with profiling at tier 3 once it gets hot, then by C2 at tier 4. A dashed arrow from C2 back to the interpreter is labelled deoptimization.
  • 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 keeps every method at tier 1 and never uses C2, which makes startup faster and warm code much slower, as this startup comparison measured.

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 2,000 times per round, on the same 1,000 numbers, and prints the average time per call for 12 rounds:

Java
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:

Output
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:+PrintCompilation, which prints a line each time the JIT compiles a method, shows how. These are the lines for countAboveFifty, from a second run:

Output
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 % sign marks an on-stack replacement (OSR). The loop inside countAboveFifty was still running when its compiled version was ready, so the JVM switched to the new code in the middle of the loop. The words "made not entrant" mean that an older version gets no new calls. With -Xint, which turns the JIT off, every round took about 15,000 ns per call, about 20 times slower than C2's code.

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 Blackhole, an object that keeps the JIT from treating the result as unused.
  • Statistics: it repeats the measurement and reports the score with an error range.
  • Profilers: with options such as -prof gc, it adds numbers such as the bytes allocated per call.

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 StringBuilder, or HashMap against 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 async-profiler to find where the time goes. A JMH result tells you how fast that code is on its own. That is a good basis for a decision, but not proof of what the whole program will gain.

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:

Shell
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 test folder with one MyBenchmark class. Running mvn clean verify builds everything into target/benchmarks.jar, and java -jar target/benchmarks.jar runs it. On JDK 23 and later, change its pom.xml before the first run. The template for JMH 1.37 adds the annotation processor with provided scope, the setup that JDK 23 stopped supporting, as the table below shows. Compiling its MyBenchmark on JDK 25 the same way, with the processor on the class path, generated no META-INF/BenchmarkList.

JMH has two parts: jmh-core, the runner, and jmh-generator-annprocess, an annotation processor that turns each @Benchmark method into generated measurement code at compile time. The examples on this page use version 1.37.

XML
<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 scope. That relied on javac finding processors on the classpath automatically, and JDK 23 turned that off. Compiling the same two files with both JDKs, with the processor on the classpath and no other flags, gave this:

Same source, processor on the classpath, no -proc flag
JDKjavac resultRunning the benchmark
21A note that "A future release of javac may disable annotation processing", and META-INF/BenchmarkList is generatedWorks
25No message, and nothing is generatedRuntimeException: ERROR: Unable to find the resource: /META-INF/BenchmarkList

The fix is annotationProcessorPaths as above, or -proc:full on the javac command line, which is what this page uses. JMH also needs benchmark classes to be in a package; in the default package the processor stops with "Benchmark class should have package other than default".

In Gradle, the processor belongs on the annotationProcessor configuration. With Gradle 8.14 and a JDK 25 toolchain, the processor jar listed under implementation generated nothing, and the same jar under annotationProcessor generated META-INF/BenchmarkList:

Kotlin
// 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 main method instead of benchmarks.jar, through this small helper, so each program runs on its own:

Java
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));
    }
}
  • forks(1) 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.
  • 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 sun.misc.Unsafe (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 with --sun-misc-unsafe-memory-access=allow, as here, is enough. The helper also passes it to the forks, so the warning stays away when a program is started without it.

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.log because it is a real computation with no side effects, so the JIT is allowed to delete it. x is a field rather than a constant so the result cannot be computed ahead of time.

Java
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:

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

discarded scored the same as the empty baseline: the call to Math.log was removed, and the number measures only the benchmark loop. Returning the value or passing it to Blackhole.consume keeps the work alive, and both cost about the same. JMH reported nothing unusual for discarded. It cannot tell a fast method from a deleted one, so comparing against an empty baseline is how you find out.

The run header (hidden here by the silent mode) said Blackhole mode: compiler (auto-detected, use -Djmh.blackhole.autoDetect=false to disable). In this mode the JIT itself keeps a consumed value alive, instead of JMH calling a real Blackhole.consume method. JMH 1.37 chooses it by checking whether the JVM accepts -XX:CompileCommand=blackhole, and its own closing note warns that the difference between Blackhole modes "can be very significant". Compare only runs made in the same mode.

Constant folding: measuring a value computed at compile time

A common first benchmark compares "Hello, " + "World" + "!" with a StringBuilder. The catch is that javac joins string literals into a single constant, so the + version does no work at all. The fix is to read the inputs from fields of a @State object.

Java
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:

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

literals returns a precomputed string, so it costs about the same as the empty baseline in the dead code table (0.301 against 0.273 ns/op, from separate runs). With fields, + and StringBuilder come out close, and their error ranges overlap. Since JDK 9, + compiles to an invokedynamic call (JEP 280) that the JVM optimizes, so the old advice that + is slow does not hold for a single expression. A loop that appends many times is a different case.

@State and @Param: inputs and a size matrix

@State classes hold inputs, so building them is not part of the measurement. @Param runs the benchmark once per value. This program looks up keys in a HashMap and a TreeMap at three sizes. The keys are visited in shuffled order, because visiting them in insertion order would let the CPU cache predict every access and hide the real cost.

Java
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:

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:

  • HashMap.get 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 boxed Integer key and for the map's own table and node.
  • TreeMap.get 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.
  • JMH crosses all @Param 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.
@State scopes
ScopeInstancesUse for
Scope.ThreadOne per benchmark threadMutable state such as counters; the usual choice when unsure
Scope.BenchmarkOne shared by all threads of a benchmark, within one forkShared data, or measuring contention on it
Scope.GroupOne per thread group (@Group)Producer and consumer benchmarks

@State has no default scope, so every state class names one. Each fork is a separate JVM, so no state is shared between forks. MapLookup uses Scope.Benchmark with one thread, where it behaves like Scope.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).

Java
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:

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
What each benchmark measured
BenchmarkSetupWhat was timed
sortFilledOnceLevel.Trial: once per forkSorting an already sorted array, for all but the first call
sortFilledEachCallLevel.Invocation: a fresh copy before every call, outside the timingSorting random data, the intended measurement
cloneThenSortCopy inside the benchmarkCopying 200,000 ints plus the sort

sortFilledOnce looks many times faster, and it is wrong. Before partitioning, Arrays.sort scans the array for runs that are already in order (tryMergeRuns in the JDK 25 source of DualPivotQuicksort). A sorted array is one run, so the call returns after a single pass. Level.Invocation gives the right answer. cloneThenSort includes the copy in the time; here copying 800 KB is small next to the sort, so the two scores are close, but for a cheaper operation the copy could be most of the score.

The Level Javadoc says this level "is only usable for benchmarks taking more than a millisecond" per call, because JMH must read the clock around every call to subtract the setup time, and for short methods that overhead distorts the result. For short methods, reset state with Level.Iteration or design the input so it does not wear out.

@Setup and @TearDown levels
LevelRuns
Level.TrialOnce per fork, before warm-up (the default)
Level.IterationBefore or after each warm-up and measurement iteration
Level.InvocationAround every single call of the benchmark method

Benchmark modes

JMH modes and what the score means
ModeScoreAnswers
Mode.Throughput (default)Operations per time unitHow many calls per second can this sustain?
Mode.AverageTimeTime per operationWhat does one call cost on average? (used on this page)
Mode.SampleTimeSampled call times with percentilesWhat do p50, p99 and the worst calls look like?
Mode.SingleShotTimeTime of one call, without warm-up iterations by defaultWhat does a cold call cost, such as start-up code?
Mode.AllAll of the aboveExploring

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 when the outliers matter more than the average.

Four more mistakes, measured

Each program below uses the same helper and settings as the rest of the page, unless its main changes one of them.

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 dividing the time by 1,000.

Java
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:

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 once and unroll or fold the loop, so the result describes the loop optimizer, not the addition. Let JMH call the method instead: its generated measurement loop passes each result to a Blackhole, which is designed to stop the JIT from merging calls like this.

forks(0): the score depends on what ran before

With forks(0), all benchmarks run in the JVM that started JMH. Three classes with identical code are called through one shared method, so the JIT's profile of the call c.next() grows with each benchmark that runs.

Java
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:

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:+PrintInlining showed why. While two types had been seen, both next methods were inlined, guided by the type profile. After the third, the line for Counter::next read "failed to inline: virtual call", so every step became a real interface call. With forks(1), all three scored between 3.520 and 3.585. In its normal output mode, JMH warns that "Non-forked runs may silently omit JVM options, mess up profilers, disable compiler hints, etc.", but silent mode hides that warning.

No warm-up

This program sets warmupIterations(0) and prints each 0.1-second measurement iteration, which a normal run averages away.

Java
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:

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 profiler (-prof gc on the command line) adds allocation per operation to the results.

Java
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:

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.norm: about 0 bytes per call when length was inlined and the Point was removed, and 32 bytes per call when it was not inlined. The time also rose from 2.147 to 6.621 ns/op, but part of that is the extra call, so the time alone does not show the allocation. The gc.count rows show the consequence: 84 garbage collections across the measured iterations, against none. The -lprof option lists the profilers JMH can use. On this machine it listed gc, stack, comp, jfr and four others as supported, and perfasm, which shows the generated machine code, as unsupported because Linux perf is not installed.

Checklist

  • Return every result or pass it to a Blackhole, and include an empty baseline so a deleted computation stands out.
  • Read inputs from @State fields, never from literals or static final constants the compiler can fold.
  • Check that the input is the same on every call; operations that change their input need Level.Invocation or Level.Iteration setup.
  • Use realistic sizes and access patterns. The HashMap results changed far more with size than any O() estimate suggests.
  • 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 forks(0) for numbers you will act on.
  • Run -prof gc when allocation matters, because time alone can hide it.
  • 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 async-profiler page.