diff --git a/docs/writing-benchmarks.md b/docs/writing-benchmarks.md new file mode 100644 index 00000000..9dc22a2d --- /dev/null +++ b/docs/writing-benchmarks.md @@ -0,0 +1,239 @@ +# Writing Benchmarks + +If you're familiar with the Java Microbenchmark Harness (JMH) toolkit, you'll find that the `kotlinx-benchmark` +library shares a similar approach to crafting benchmarks. This compatibility allows you to seamlessly run your +JMH benchmarks written in Kotlin on various platforms with minimal, if any, modifications. + +Like JMH, kotlinx-benchmark is annotation-based, meaning you configure benchmark execution behavior using annotations. +The library then extracts metadata provided through annotations to generate code that benchmarks the specified code +in the desired manner. + +To get started, let's examine a simple example of a multiplatform benchmark: + +```kotlin +import kotlinx.benchmark.* + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(BenchmarkTimeUnit.MILLISECONDS) +@Warmup(iterations = 10, time = 500, timeUnit = BenchmarkTimeUnit.MILLISECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) +@State(Scope.Benchmark) +class ExampleBenchmark { + + // Parameterizes the benchmark to run with different list sizes + @Param("4", "10") + var size: Int = 0 + + private val list = ArrayList() + + // Prepares the test environment before each benchmark run + @Setup + fun prepare() { + for (i in 0..