Sub topic 16
Explaining results with profilers
A JMH score tells you how fast a method ran. It does not tell you why. This chapter shows how to attach JMH's built-in profilers to a run so you can explain a number, especially one that surprises you. It assumes you can build and run a JMH jar, read score and error, and use @State, as covered in earlier chapters.
What a profiler does in JMH
A JMH profiler is an observer attached to the forked benchmark JVM. It collects extra data during the run and prints it next to the score, in the same results table. You enable one with the -prof flag, and you can list the profilers available on your machine with -lprof:
java -jar target/benchmarks.jar -lprofThe common built-in profilers:
| Profiler | Flag | What it reports | Notes |
|---|---|---|---|
| GC | `-prof gc` | Allocation rate, bytes allocated per operation, GC count and time | Low overhead, works everywhere |
| Stack | `-prof stack` | Sampled stack traces, grouped by method and line | Statistical, coarse |
| Class loading | `-prof cl` | Classes loaded and unloaded | Useful for startup-style benchmarks |
| Compiler | `-prof comp` | Time spent in JIT compilation | Shows whether compilation leaks into measurement |
| perfasm | `-prof perfasm` | Hot assembly instructions | Linux only, needs `perf` and usually a disassembler plugin |
Some profilers need external tools, so the list from -lprof may be shorter than the table. This chapter concentrates on the GC profiler because it works on any machine and explains the most common surprise: one benchmark is slower than another because it allocates more.
Profilers need a forked JVM to attach to. Running with -f 0 (no fork) disables or breaks most of them, so keep at least one fork.
A benchmark worth profiling
The class below builds one string from 50 parts in two ways. Both return the finished string, so the JIT cannot discard the work.
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
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;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
public class ConcatBenchmark {
private String[] parts;
@Setup
public void setUp() {
parts = new String[50];
for (int i = 0; i < parts.length; i++) {
parts[i] = "part-" + i;
}
}
@Benchmark
public String plusEquals() {
String result = "";
for (String part : parts) {
result += part;
}
return result;
}
@Benchmark
public String stringBuilder() {
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(part);
}
return sb.toString();
}
}Run both benchmarks with the GC profiler:
java -jar target/benchmarks.jar ConcatBenchmark -prof gcWithout the profiler you would see that plusEquals has a larger score in nanoseconds per operation. With it, JMH adds secondary result rows for each benchmark. The ones you will use most are:
| Row | Unit | Meaning |
|---|---|---|
| `gc.alloc.rate` | MB/sec | Heap allocated per second of wall-clock time |
| `gc.alloc.rate.norm` | B/op | Heap allocated per benchmark call |
| `gc.count` | counts | Number of GC events during measurement |
| `gc.time` | ms | Total time spent in those GC events |
The row to read first is gc.alloc.rate.norm. Each += creates a new string and copies everything built so far, so plusEquals allocates far more bytes per call than stringBuilder, which grows one buffer. The exact numbers depend on your JVM and machine, so compare the two rows on your own run instead of expecting fixed values.
Why the normalized row matters
gc.alloc.rate is bytes per second. A faster benchmark does more calls per second, so it can show a higher rate even when each call allocates less. That makes the raw rate misleading when you compare benchmarks.
gc.alloc.rate.norm divides by the number of operations, so it answers the question "how much garbage does one call create?". It is stable across machines and across benchmark modes, because it counts bytes and not time. Use it for comparisons and for regression checks.
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
@Fork(1)
public class EscapeBenchmark {
private int x = 7;
private static final class Point {
final int a;
final int b;
Point(int a, int b) {
this.a = a;
this.b = b;
}
}
@Benchmark
public int pointSum() {
Point p = new Point(x, x + 1);
return p.a + p.b;
}
}You might expect pointSum to report 16 bytes or more per operation, the size of a small object. With -prof gc it often reports close to zero. The JIT's escape analysis can prove that p never leaves the method and replace the object with two local values. The profiler is showing you that the allocation you wrote in the source does not exist in the compiled code. If you want the object to exist, make it escape by returning it or passing it to a Blackhole.
Reading `gc.count` and `gc.time`
gc.count and gc.time tell you whether garbage collection affected the score. If gc.count is zero, the heap never filled during measurement and GC cost nothing. A nonzero gc.time is time the benchmark thread was paused or competed with collector threads, so it is included in your score.
A high gc.count is not a bug in the benchmark. It is a real cost of allocating a lot, and it often explains why the gap between two implementations is wider in production than in a lab with a large heap. Keep the heap settings the same across the runs you compare. For example, you can pass -jvmArgs "-Xms512m -Xmx512m" on the command line.
Using the stack profiler for "where does the time go"
The allocation numbers explain one cause. When the cause is not allocation, -prof stack samples the benchmark thread's stack during measurement and reports which methods appear most often:
java -jar target/benchmarks.jar ConcatBenchmark.plusEquals -prof stackThe output groups samples by thread state and by top frames. It helps when a benchmark calls into library code and you need to know which part dominates. It is a sampling profiler that cannot see inside inlined code well, so treat it as a hint and not as a measurement. Samples are also affected by safepoint bias: they tend to land where the JVM can pause a thread, not exactly where time is spent.
For finer detail, -prof perfasm on Linux shows hot assembly, and -prof async can drive the async-profiler tool if you have installed it. Both depend on tools outside JMH, so check -lprof and the JMH sample documentation before relying on them.
A workflow for surprising scores
Follow the loop in order. State the hypothesis before you rerun, for example "the builder version allocates about a tenth as many bytes per call". If the profiler disagrees, your explanation was wrong, and a wrong explanation you have checked is better than a right-sounding one you have not.
Gotchas
- A profiler can change what it measures.
gcis cheap, butstackandperfasmadd overhead. Do not compare a score taken with a profiler to one taken without. - Profile after the score is trustworthy. If the error is large or the forks disagree, fix the benchmark first.
- Profilers report on the measurement phase of the forked JVM. Warmup allocation is not counted, which is what you want.
- Normalized values are averages. A benchmark that allocates only on some inputs shows a blend, so use
@Paramto separate the cases. - A near-zero
gc.alloc.rate.normis a finding, not proof of a fast algorithm. Check whether escape analysis removed work that your real code would still do.
Exercise
You run two benchmarks with -prof gc. Benchmark A shows gc.alloc.rate of 4000 MB/sec and gc.alloc.rate.norm of 48 B/op. Benchmark B shows gc.alloc.rate of 1500 MB/sec and gc.alloc.rate.norm of 240 B/op. Which allocates more garbage per call, and why can the raw rate mislead you here?
Show answer
Benchmark B allocates more per call (240 B/op against 48 B/op). Benchmark A has the higher raw rate only because it completes many more calls per second, so each of its cheap calls adds up quickly. The normalized row divides by the number of operations, which makes the two comparable.
Exercise
A benchmark creates a small object inside the method and uses its fields, but -prof gc reports gc.alloc.rate.norm of about 0 B/op. What is the most likely explanation, and how would you check that the object cost is real in your use case?
Show answer
Escape analysis most likely proved the object never escapes the method and removed the allocation, so the compiled code has no object. To measure the allocation, make the object escape, for example by returning it from the benchmark method or by passing it to Blackhole.consume, then rerun with -prof gc and check that the bytes per operation are no longer near zero.