Profiling
- Kotlin course
- Expert
- Lesson 37/47
- 5 min
Learn performance measurement with JVM profiling and JMH.
What is profiling?
Profiling measures which part of a program is slow. On Kotlin/JVM the most common tool is the JMH (Java Microbenchmark Harness) library.
JMH marks a method with @Benchmark and measures it at nanosecond precision. The result is reported as ns/op (nanoseconds per operation). A good benchmark includes warmup iterations and several measurements. The profileInfo model in this lesson shows the concept with a simple example.
JMH setup
JMH is added to a project with a Gradle plugin. Benchmark methods are marked with @Benchmark; @BenchmarkMode sets the measurement mode.
Example: @Benchmark fun work(): Int { return 42 }. JMH runs this method many times, starting measurement after a warmup lap. Results can be exported as CSV or JSON. A bad benchmark (allocating inside the measured code) gives misleading numbers, so benchmark methods are kept simple.
Practice Write profileInfo
Define fun profileInfo(): String. It should return "JMH". In main, write println(profileInfo()).
Starter code
// add the profileInfo function
fun main() {
// print the profiling info
}Sample solution
fun profileInfo(): String = "JMH"
fun main() {
println(profileInfo())
}Expected output
JMH
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does JMH measure?
JMH measures small-scale performance.- Disk I/O
- Memory usage
- Micro performance Correct answer
- Network latency
Explanation: JMH measures micro performance at method level.
2 Complete the @Benchmark line
@Benchmark fun ____(): Int { return 42 }
@Benchmark fun work(): Int { return 42 }
Explanation: @Benchmark fun work() is the method JMH measures.
3 Match the JMH parts
| Term | Meaning |
|---|---|
JMH |
Benchmark library |
@Benchmark |
Method marker |
@BenchmarkMode |
Measure mode |
ns/op |
Nanos per op |