Sub topic 1
Java Microbenchmarks with JMH: Why Hand-Written Timing Loops Mislead
Prerequisites
You should know basic Java classes, annotations, Maven commands, and the idea that the JVM compiles frequently used code at runtime.
Why Hand-Written Timing Loops Mislead
A simple timing loop measures more than the operation you care about:
long start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
calculate(i);
}
long elapsed = System.nanoTime() - start;The result includes loop overhead, garbage collection, operating-system scheduling, and timer noise. The JVM may also optimize the loop while it runs. One execution can therefore differ greatly from the next.
Warmup and JIT Compilation
The Java Virtual Machine (JVM) starts by interpreting bytecode. Its just-in-time (JIT) compiler later turns frequently executed code into optimized machine code. A timing loop can measure both slow, uncompiled code and fast, compiled code.
A reliable benchmark needs separate warmup runs before measurement. It also needs repeated measurements and independent JVM processes.
What JMH Does for You
JMH, the Java Microbenchmark Harness, automates warmup, measurement iterations, process forks, result handling, and common JVM pitfalls. It also prevents many optimizations from invalidating a test.
Creating a JMH Project
The Maven archetype creates a project with the JMH dependencies and packaging configuration:
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample \
-DartifactId=benchmarks \
-Dversion=1.0
cd benchmarks
mvn clean verify
java -jar target/benchmarks.jarYour First `@Benchmark` Method
A method marked @Benchmark is the operation JMH measures. Return the result so the JVM cannot easily remove the calculation.
package org.sample;
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 java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SumBenchmark {
@Benchmark
public long sum() {
long total = 0;
for (int i = 0; i < 1_000; i++) {
total += i;
}
return total;
}
}Exercise
Why should a benchmark use warmup iterations?
Show answer
Warmup lets the JVM reach its optimized, JIT-compiled state before JMH records measurements.