Benchmarks
suggest changeA benchmark answers one narrow question: how long does this piece of code take (or how much does it allocate) under these conditions? You write one to choose between two implementations, to check that an optimization actually helped, or to catch a regression before it ships.
On the JVM this is harder than it looks. The same Kotlin function starts out interpreted, gets compiled by the JIT once it is hot, and may be recompiled later. The JIT also deletes work whose result nobody uses. A naive stopwatch measures all of that mixed together.
This article covers:
- quick timing with
kotlin.timeand when that's good enough - why naive timing lies: warm-up and dead-code elimination
- a small hand-written harness for rough comparisons
- JMH (Java Microbenchmark Harness): annotations, modes, state and setup levels, the command line and the Runner API
- measuring allocation with
-prof gc - running JMH without a build plugin, and extra kotlinx-benchmark configuration
- reading and comparing results
Performance shows how to set up JMH through the kotlinx-benchmark Gradle plugin and lists the basic benchmark pitfalls; this article goes further into writing and running benchmarks. To find which code is worth benchmarking in the first place, use a profiler (see Profiling).
Quick timing with kotlin.time
For code that runs for many milliseconds or longer (a whole request, a batch job, a test suite), plain timing is fine. The standard library has three tools for it, all using a monotonic clock that isn't affected by changes to the wall clock:
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
import kotlin.time.TimeSource
fun fib(n: Int): Long = if (n < 2) n.toLong() else fib(n - 1) + fib(n - 2)
fun main() {
// just the duration
val d = measureTime { fib(30) }
println("fib(30) took $d")
// the duration and the result
val (value, took) = measureTimedValue { fib(32) }
println("fib(32) = $value in ${took.inWholeMilliseconds} ms")
// a time mark, for timing across statements
val mark = TimeSource.Monotonic.markNow()
val sorted = List(1_000_000) { (it * 7919) % 1_000_003 }.sorted()
println("sorted ${sorted.size} in ${mark.elapsedNow()}")
}
fib(30) took 5.184900ms
fib(32) = 2178309 in 10 ms
sorted 1000000 in 509.818700ms
All three return a kotlin.time.Duration, which prints in a readable unit and converts with inWholeMilliseconds, inWholeMicroseconds or toDouble(DurationUnit.NANOSECONDS). Don't use System.currentTimeMillis() for timing: it follows the wall clock, which can jump, and its resolution can be coarse. System.nanoTime() is what TimeSource.Monotonic uses on the JVM.
Why naive timing lies
Warm-up
Time the same work several times in one JVM and the first run is much slower:
import kotlin.time.measureTime
fun parseCsvLine(line: String): Int = line.split(',').sumOf { it.trim().toInt() }
fun main() {
val lines = List(10_000) { i -> "$i, ${i * 2}, ${i * 3}, ${i % 7}" }
var sink = 0L
repeat(10) { round ->
val took = measureTime {
for (line in lines) sink += parseCsvLine(line)
}
println("round $round: $took")
}
println("checksum $sink")
}
round 0: 15.907100ms
round 1: 2.608100ms
round 2: 2.679600ms
round 3: 2.121600ms
round 4: 2.315300ms
round 5: 2.211100ms
round 6: 1.905800ms
round 7: 1.705500ms
round 8: 3.308900ms
round 9: 1.628600ms
Round 0 is about 7x slower than the rest. During that round classes are loaded and the code runs in the interpreter until the JIT compiles parseCsvLine, split and toInt. Later rounds still move around: the JIT compiles some methods again with better optimizations, the GC runs now and then, and other processes compete for the CPU. A single measurement of a short operation tells you almost nothing.
Dead-code elimination
The JIT removes computations whose results are never used. If your benchmark throws the result away, you may be timing an empty loop. Here is a JMH benchmark (JMH is introduced below) that measures the same function three ways:
package bench
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
open class DeadCodeBenchmark {
private var n = 1000
private fun sumOfSquares(n: Int): Long {
var sum = 0L
for (i in 1..n) sum += i.toLong() * i
return sum
}
@Benchmark
fun baseline() {
// empty: the cost of the harness itself
}
@Benchmark
fun wrong() {
sumOfSquares(n) // result unused: the JIT may remove the loop
}
@Benchmark
fun returned(): Long = sumOfSquares(n)
@Benchmark
fun blackhole(bh: Blackhole) {
bh.consume(sumOfSquares(n))
bh.consume(sumOfSquares(n + 1))
}
}
Benchmark Mode Cnt Score Error Units
DeadCodeBenchmark.baseline avgt 5 0.376 ± 0.188 ns/op
DeadCodeBenchmark.blackhole avgt 5 862.874 ± 311.813 ns/op
DeadCodeBenchmark.returned avgt 5 448.973 ± 160.894 ns/op
DeadCodeBenchmark.wrong avgt 5 0.851 ± 0.578 ns/op
wrong is as fast as the empty baseline: a loop of 1000 multiplications in under a nanosecond means the loop is gone. Returning the value (returned) or passing it to a Blackhole (blackhole, which does the work twice) keeps the work alive. Notice also that n is a field, not a constant: with sumOfSquares(1000) the JIT could compute the answer once and reuse it.
A minimal hand-written harness
If you only want a rough comparison and don't want to add a dependency, a small harness that warms up, takes several samples, reports the median and stores every result in a @Volatile field avoids the worst mistakes:
import kotlin.time.Duration
import kotlin.time.TimeSource
@Volatile var sink: Any? = null // results go here so the JIT can't drop the work
fun bench(name: String, warmupRounds: Int = 5, rounds: Int = 10, opsPerRound: Int = 10_000, op: () -> Any?) {
repeat(warmupRounds) { repeat(opsPerRound) { sink = op() } }
val perOp = mutableListOf<Duration>()
repeat(rounds) {
val mark = TimeSource.Monotonic.markNow()
repeat(opsPerRound) { sink = op() }
perOp += mark.elapsedNow() / opsPerRound
}
perOp.sort()
val median = perOp[perOp.size / 2]
println("%-14s median %8.1f ns/op (min %.1f, max %.1f)".format(
name, median.toDouble(nanos), perOp.first().toDouble(nanos), perOp.last().toDouble(nanos)))
}
val nanos = kotlin.time.DurationUnit.NANOSECONDS
fun main() {
val words = List(100) { "word$it" }
bench("plus in loop") {
var s = ""
for (w in words) s += w
s
}
bench("buildString") {
buildString { for (w in words) append(w) }
}
bench("joinToString") {
words.joinToString("")
}
}
plus in loop median 2278.0 ns/op (min 2136.0, max 3802.0)
buildString median 650.0 ns/op (min 631.0, max 775.0)
joinToString median 722.0 ns/op (min 695.0, max 741.0)
The median is more robust than the mean against a round that hit a GC pause. Still, this harness has real weaknesses:
- All benchmarks run in one JVM, so the first one can change how the JIT compiles code used by the later ones (for example, a call site that sees several lambda types stops being inlined). Reordering the calls can change the results.
- The JIT may optimize across the
repeatloop in ways that real code never sees. - There is no error estimate, so you can't tell a real difference from noise.
For anything you will base a decision on, use JMH.
JMH
JMH is the benchmark harness developed by the OpenJDK team. It generates code around your benchmark methods that handles warm-up, runs every benchmark in a fresh forked JVM, prevents dead-code elimination of returned values, and reports a confidence interval. It works with any JVM language; in Kotlin the benchmark classes must be open (JMH subclasses them), which the kotlinx-benchmark plugin does for you through allopen, as shown in Performance.
Annotations
Annotations go on the class (they apply to all its benchmarks) or on individual methods:
| Annotation | Meaning |
|---|---|
@Benchmark |
a method to measure |
@State(Scope.Benchmark / Thread / Group) |
the class holds state; Thread gives each benchmark thread its own instance, Benchmark shares one |
@BenchmarkMode(Mode.X) |
what to measure, see below |
@OutputTimeUnit(TimeUnit.X) |
unit for reported scores |
@Warmup(iterations, time) |
unmeasured iterations to let the JIT settle |
@Measurement(iterations, time) |
measured iterations (time is per iteration, in seconds by default) |
@Fork(n) |
run in n fresh JVMs; jvmArgsAppend = ["-Xmx2g"] adds JVM flags |
@Threads(n) |
run the benchmark from n threads at once |
@Param("10", "100") |
run once per value; works on var properties of String, primitive or enum types |
@Setup(level) / @TearDown(level) |
untimed code to prepare and clean up state |
@OperationsPerInvocation(n) |
the method does n operations; divide the score by n |
The modes:
| Mode | Reports | Use for |
|---|---|---|
Mode.Throughput (thrpt) |
operations per time unit | "how many per second can we do" |
Mode.AverageTime (avgt) |
time per operation | the usual choice for comparisons |
Mode.SampleTime (sample) |
distribution of times, with percentiles | spotting outliers, p99 latency |
Mode.SingleShotTime (ss) |
time of a single call, no warm-up loop | cold-start cost, expensive one-off operations |
Setup levels and mutable state
@Setup takes a level that says how often it runs:
Level.Trial(the default): once per fork, before all iterations. Use it to build input data.Level.Iteration: before each measurement iteration.Level.Invocation: before every single call of the benchmark method.
The level matters when a benchmark modifies its input. Sorting an array in place is the classic trap: after the first call the array is sorted, and every later call measures sorting already-sorted data:
package bench
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import kotlin.random.Random
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
open class SortNoReset {
private lateinit var work: IntArray
@Setup
fun setup() {
work = IntArray(10000) { Random(it).nextInt() }
}
@Benchmark
fun sortInPlace(): IntArray {
work.sort() // sorted after the first call
return work
}
}
Two ways to fix it: restore the input with @Setup(Level.Invocation), or copy it inside the benchmark and measure the copy separately so you can subtract it:
package bench
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import kotlin.random.Random
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
open class SortBenchmark {
@Param("10000")
var size: Int = 0
private lateinit var original: IntArray // never modified
private lateinit var work: IntArray // reset before every call
@Setup(Level.Trial)
fun createData() {
original = IntArray(size) { Random(it).nextInt() }
work = IntArray(size)
}
// Level.Invocation: runs before *every* call of a benchmark method, untimed
@Setup(Level.Invocation)
fun resetWork() {
original.copyInto(work)
}
@Benchmark
fun sortInPlace(): IntArray {
work.sort()
return work
}
@Benchmark
fun copyThenSort(): IntArray {
val a = original.copyOf() // copy cost is part of the measurement...
a.sort()
return a
}
@Benchmark
fun copyOnly(): IntArray = original.copyOf() // ...so measure it separately
}
Benchmark (size) Mode Cnt Score Error Units
SortBenchmark.copyOnly 10000 avgt 5 2.841 ± 1.072 us/op
SortBenchmark.copyThenSort 10000 avgt 5 359.611 ± 231.595 us/op
SortBenchmark.sortInPlace 10000 avgt 5 330.755 ± 47.572 us/op
SortNoReset.sortInPlace N/A avgt 5 1.429 ± 0.315 us/op
The broken version claims sorting takes 1.4 µs; the real cost is about 330 µs. The copy costs under 3 µs, so here both fixes give the same answer. Level.Invocation adds timestamps around every call, so use it only when one call takes at least a millisecond or so; for faster operations prefer the copy-and-subtract approach.
Command-line options
A JMH build produces a runnable program whose main class is org.openjdk.jmh.Main. Its arguments override the annotations, which is handy for quick experiments:
java -jar benchmarks.jar -h # all options
java -jar benchmarks.jar -l # list benchmarks
java -jar benchmarks.jar Sort # run benchmarks matching a regex
java -jar benchmarks.jar Sort -f 1 -wi 3 -i 5 -w 1s -r 1s # forks, warm-up/measurement iterations and times
java -jar benchmarks.jar StringBenchmark -p count=10,1000 # override a @Param
java -jar benchmarks.jar Sort -t 4 # 4 threads
java -jar benchmarks.jar Sort -rf json -rff sort.json # machine-readable results
java -jar benchmarks.jar -lprof # list available profilers
java -jar benchmarks.jar StringBenchmark -prof gc # attach the GC profiler
The last output table above came from -f 1 -wi 3 -i 5 -w 1s -r 1s, since SortBenchmark itself has no @Fork, @Warmup or @Measurement annotations (the defaults are 5 forks of 5 warm-up and 5 measurement iterations of 10 seconds each, about 8 minutes per benchmark).
Running from code with the Runner API
You can also start JMH from your own main function, for example to run a fixed set of benchmarks with fixed settings or to post-process the results:
package bench
import org.openjdk.jmh.results.format.ResultFormatType
import org.openjdk.jmh.runner.Runner
import org.openjdk.jmh.runner.options.OptionsBuilder
import org.openjdk.jmh.runner.options.TimeValue
fun main() {
val options = OptionsBuilder()
.include(SortBenchmark::class.java.simpleName) // regex matched against benchmark names
.warmupIterations(3)
.warmupTime(TimeValue.seconds(1))
.measurementIterations(5)
.measurementTime(TimeValue.seconds(1))
.forks(1)
.resultFormat(ResultFormatType.JSON)
.result("sort.json")
.build()
val results = Runner(options).run()
for (r in results) {
val p = r.primaryResult
println("%-40s %10.2f %s".format(r.params.benchmark, p.score, p.scoreUnit))
}
}
Benchmark (size) Mode Cnt Score Error Units
SortBenchmark.copyOnly 10000 avgt 5 2.953 ± 0.381 us/op
SortBenchmark.copyThenSort 10000 avgt 5 445.803 ± 258.099 us/op
SortBenchmark.sortInPlace 10000 avgt 5 513.179 ± 234.036 us/op
Benchmark result is saved to sort.json
bench.SortBenchmark.copyOnly 2.95 us/op
bench.SortBenchmark.copyThenSort 445.80 us/op
bench.SortBenchmark.sortInPlace 513.18 us/op
JMH prints its usual progress and summary table, then run() returns a collection of RunResult objects you can inspect.
Measuring allocation with -prof gc
Time measurements are noisy; allocation counts are not. The GC profiler adds allocation metrics to every benchmark. This benchmark builds a string from count words in three ways:
package bench
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
open class StringBenchmark {
@Param("10", "100")
var count: Int = 0
private lateinit var words: List<String>
@Setup
fun setup() {
words = List(count) { "word$it" }
}
@Benchmark
fun plusInLoop(): String {
var s = ""
for (w in words) s += w
return s
}
@Benchmark
fun builder(): String = buildString { for (w in words) append(w) }
@Benchmark
fun join(): String = words.joinToString("")
}
Running it with -prof gc (output trimmed to the time and gc.alloc.rate.norm rows):
Benchmark (count) Mode Cnt Score Error Units
StringBenchmark.builder 10 avgt 10 175.672 ± 67.801 ns/op
StringBenchmark.builder:gc.alloc.rate.norm 10 avgt 10 272.001 ± 0.001 B/op
StringBenchmark.builder 100 avgt 10 1264.128 ± 248.574 ns/op
StringBenchmark.builder:gc.alloc.rate.norm 100 avgt 10 3032.009 ± 0.002 B/op
StringBenchmark.join 10 avgt 10 133.939 ± 31.951 ns/op
StringBenchmark.join:gc.alloc.rate.norm 10 avgt 10 272.001 ± 0.001 B/op
StringBenchmark.join 100 avgt 10 1245.072 ± 389.135 ns/op
StringBenchmark.join:gc.alloc.rate.norm 100 avgt 10 3032.009 ± 0.003 B/op
StringBenchmark.plusInLoop 10 avgt 10 135.698 ± 18.630 ns/op
StringBenchmark.plusInLoop:gc.alloc.rate.norm 10 avgt 10 712.001 ± 0.001 B/op
StringBenchmark.plusInLoop 100 avgt 10 3506.215 ± 1706.972 ns/op
StringBenchmark.plusInLoop:gc.alloc.rate.norm 100 avgt 10 33648.025 ± 0.012 B/op
This run was on a busy machine, and the time scores have large error bars: for 10 words the three versions can't be told apart. The allocation numbers are exact and tell the story anyway. += in a loop copies the growing string on every step, so its allocation grows quadratically: 2.6x more than buildString for 10 words and 11x more for 100. That is why plusInLoop falls behind as count grows.
The rows to look at:
gc.alloc.rate.norm: bytes allocated per operation. The most useful number; compare it between versions.gc.alloc.rate: MB per second. Depends on speed, so less useful for comparisons.gc.count,gc.time: how many collections happened during measurement and how long they took.
Other built-in profilers: stack (simple sampling of hot methods), comp (JIT compilation time), cl (class loading), jfr (records a Java Flight Recorder file per fork), async (async-profiler, if its native library is installed) and, on Linux, perfnorm (hardware counters such as cache misses per operation) and perfasm (the generated assembly of hot code).
Running JMH without a build plugin
The kotlinx-benchmark and me.champeau.jmh Gradle plugins hide the build steps, but it helps to know what they do. JMH's annotation processor only sees Java sources, so for Kotlin the benchmark harness is generated from compiled bytecode instead:
JMH=jmh-core-1.37.jar:jopt-simple-5.0.4.jar:commons-math3-3.6.1.jar
GEN=$JMH:jmh-generator-bytecode-1.37.jar:jmh-generator-reflection-1.37.jar:jmh-generator-asm-1.37.jar:asm-9.0.jar
# 1. compile the Kotlin benchmark classes
kotlinc src -cp jmh-core-1.37.jar -d classes
# 2. generate the harness (Java sources + META-INF/BenchmarkList) from the bytecode
java -cp $GEN org.openjdk.jmh.generators.bytecode.JmhBytecodeGenerator \
classes gen/java gen/resources default
# 3. compile the generated Java code next to the Kotlin classes
javac -cp jmh-core-1.37.jar:classes -d classes $(find gen/java -name '*.java')
cp -r gen/resources/* classes/
# 4. run (the Kotlin stdlib must be on the classpath: forked JVMs reuse it)
java -cp classes:$JMH:kotlin-stdlib.jar org.openjdk.jmh.Main DeadCodeBenchmark
On Windows use ; instead of : as the classpath separator. Packing classes and the dependency jars into one jar with Main-Class: org.openjdk.jmh.Main gives the usual benchmarks.jar.
More kotlinx-benchmark configuration
With the kotlinx-benchmark plugin you can define several named configurations, for example a quick smoke run next to the full one. Each configuration gets its own Gradle task:
// build.gradle.kts
benchmark {
targets {
register("main")
}
configurations {
named("main") {
warmups = 5
iterations = 10
iterationTime = 1
iterationTimeUnit = "s"
mode = "avgt"
outputTimeUnit = "ns"
reportFormat = "json"
}
register("smoke") {
include("StringBenchmark") // regex, like JMH's include
exclude(".*plusInLoop.*")
param("count", 10) // override a @Param
warmups = 1
iterations = 3
iterationTime = 300
iterationTimeUnit = "ms"
advanced("jvmForks", 1)
advanced("jvmProfiler", "gc") // same as -prof gc
}
}
}
./gradlew benchmark runs the main configuration and ./gradlew smokeBenchmark the smoke one. Reports are written to build/reports/benchmarks/<configuration>/<timestamp>/.
For Kotlin Multiplatform projects, import the annotations from kotlinx.benchmark instead of org.openjdk.jmh.annotations (@State, @Benchmark, @Setup, @Param, Blackhole, ...). On the JVM they map to the JMH ones, and the same benchmark source also runs on Kotlin/JS, Kotlin/Wasm and Kotlin/Native targets.
Reading and comparing results
- Score ± Error.
Erroris half the width of a 99.9% confidence interval. If the intervals of two benchmarks overlap, you have not shown a difference. Run more forks or iterations, or quiet the machine. - Look at proportions, not absolute numbers. Scores depend on the CPU, the JDK, the JVM flags and what else is running. Compare versions measured in the same run on the same machine.
- Keep a baseline. An empty benchmark or the current implementation gives you something to compare against. A score near the empty baseline means the JIT removed your code.
- Use several input sizes.
@Paramwith small and large values catches algorithms that win on small inputs and lose on large ones, asplusInLoopdoes above. - Save results.
-rf jsonoutput can be compared later or visualized (for example with the online JMH Visualizer); kotlinx-benchmark writes JSON by default. - Check that the benchmark tests what you think. Print or assert the result once in a unit test, and make sure inputs aren't constants the JIT can fold.
Benchmarking in CI
Shared CI machines are noisy: neighbors on the same host, CPU frequency scaling and thermal throttling easily cause 10-30% swings. Some practical rules:
- Run benchmarks on a dedicated machine, or at least compare the old and new versions in the same CI job so they see the same conditions.
- Gate builds on large regressions only (say, more than 20% slower with non-overlapping error intervals), not on small differences.
- Track
gc.alloc.rate.normin CI. It barely varies between runs, so even a small increase is a real change. - Keep the CI configuration short (a
smokeconfiguration with 1 fork and few iterations) and run the full configuration by hand when investigating.
What not to microbenchmark
JMH measures small pieces of code in isolation. It can't tell you:
- End-to-end latency of a service. Use a load-testing tool such as k6, wrk or Gatling against a running instance.
- Startup time of a CLI tool. Each run is a cold JVM; time whole process runs with a tool like
hyperfine, or useMode.SingleShotTimewith many forks. - Suspending code in a realistic setting. A
@Benchmarkmethod can't besuspend; wrapping the call inrunBlockingmeasures the dispatcher overhead too. Benchmark the CPU-bound parts directly and measure concurrency with a load test.
Checklist
- Profile first, so you benchmark code that matters.
- Use JMH (directly or via kotlinx-benchmark) for anything under a second per call; use
measureTimeonly for long operations. - Return results or pass them to a
Blackhole; keep inputs in@Statefields, not constants. - Reset mutated input with
@Setup(Level.Invocation)(slow operations) or copy and subtract (fast ones). - Use
@Paramfor several input sizes, and include a baseline. - Add
-prof gcand comparegc.alloc.rate.norm. - Trust differences only when error intervals don't overlap, and measure old and new versions in the same run.