Microbenchmarking Java code with JMH

Photo by Kolleen Gladden on Unsplash

Gradle configuration

plugins {
id("me.champeau.jmh").version("0.6.6")
}
  • gradle jmh: Runs all benchmarks
  • gradle jmhJar: Generates a portable JAR that you can run on a different machine

Writing a JMH benchmark

@Fork(value = 1, warmups = 1)
@Warmup(iterations = 1)
@Measurement(iterations = 1)
@OutputTimeUnit(TimeUnit.SECONDS)
public class Benchmark {
@Benchmark
public static void oneBenchmark() {
// do something
}
}

“Consuming” results

public class Benchmark {
@Benchmark
public static void oneBenchmark() {
// assume an object under test
tested.get();
}
}
public class Benchmark {
@Benchmark
public static void oneBenchmark(Blackhole blackhole) {f
// the code under test is always executed
blackhole.consume(tested.get());
}
}

Further reading

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mihai Bojin

Mihai Bojin

Software Engineer at heart, Manager by day, Indie Hacker at night. Writing about DevOps, Software engineering, and Cloud computing. Opinions my own.