CodeBlanks Logo Icon CodeBlanks

JMH

Learn to benchmark with JMH.

Microbenchmarking with JMH

JMH (Java Microbenchmark Harness) is a framework for measuring small code pieces accurately. Warmup rounds trigger the JIT compiler and measurement rounds collect the result. This avoids misleading measurements.

JMH measures methods marked with @Benchmark. @State carries state and Blackhole prevents dead code elimination. For correct benchmarks warmup and iteration counts are given explicitly.

Warmup and measurement rounds

JMH runs in two phases: first warmup rounds let the JIT compile hot methods; their result is not counted. Then measurement rounds collect timings. Without warmup the measurement includes cold compilation and is wrong.

Round counts are set with @Warmup(iterations=3) and @Measurement(iterations=5). The result is presented statistically: average, error margin.

Practice Write the BenchmarkRunner class

Define class BenchmarkRunner with static int iterations = 5; and static int warmup = 3; fields and an empty void measure() {} method. In main print System.out.println("warmup=" + warmup + " iters=" + iterations);.

Starter code

Main.java
// Define the BenchmarkRunner class: iterations and warmup fields, measure method

// main: print warmup and iterations values

Sample solution

Main.java
class BenchmarkRunner {
    static int iterations = 5;
    static int warmup = 3;
    void measure() {}
    public static void main(String[] args) {
        System.out.println("warmup=" + warmup + " iters=" + iterations);
    }
}

Expected output

warmup=3 iters=5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is JMH used for?

  • Database management
  • Graphics rendering
  • Web server
  • Microbenchmarking Correct answer

Explanation: JMH measures small code pieces accurately.

2 Complete the benchmark annotation

Question
@____
public void measure() {}
Answer
@Benchmark
public void measure() {}

Explanation: @Benchmark marks the measured method.

3 Match the JMH concepts

Term Meaning
@Benchmark Measured method
@State State carrier
Blackhole Prevents dead code
@Warmup Warmup round

All lessons in Expert