Benchmarks

suggest change

A 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:

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:

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:

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:

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

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:

What not to microbenchmark

JMH measures small pieces of code in isolation. It can't tell you:

Checklist

  1. Profile first, so you benchmark code that matters.
  2. Use JMH (directly or via kotlinx-benchmark) for anything under a second per call; use measureTime only for long operations.
  3. Return results or pass them to a Blackhole; keep inputs in @State fields, not constants.
  4. Reset mutated input with @Setup(Level.Invocation) (slow operations) or copy and subtract (fast ones).
  5. Use @Param for several input sizes, and include a baseline.
  6. Add -prof gc and compare gc.alloc.rate.norm.
  7. Trust differences only when error intervals don't overlap, and measure old and new versions in the same run.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents