Skip to content

Instantly share code, notes, and snippets.

@olegcherr
Last active May 14, 2022 10:21
Show Gist options
  • Save olegcherr/b62a09aba1bff643a049 to your computer and use it in GitHub Desktop.
Save olegcherr/b62a09aba1bff643a049 to your computer and use it in GitHub Desktop.
Simple Kotlin micro-benchmarking tool (Android supported)
package azagroup.test
import java.util.ArrayList
/**
* Iterates provided by [callback] code [ITERATIONS]x[TEST_COUNT] times.
* Performs warming by iterating [ITERATIONS]x[WARM_COUNT] times.
*/
fun simpleMeasureTest(
ITERATIONS: Int = 1000,
TEST_COUNT: Int = 10,
WARM_COUNT: Int = 2,
callback: ()->Unit
) {
val results = ArrayList<Long>()
var totalTime = 0L
var t = 0
println("$PRINT_REFIX -> go")
while (++t <= TEST_COUNT + WARM_COUNT) {
val startTime = System.currentTimeMillis()
var i = 0
while (i++ < ITERATIONS)
callback()
if (t <= WARM_COUNT) {
println("$PRINT_REFIX Warming $t of $WARM_COUNT")
continue
}
val time = System.currentTimeMillis() - startTime
println(PRINT_REFIX+" "+time.toString()+"ms")
results.add(time)
totalTime += time
}
results.sort()
val average = totalTime / TEST_COUNT
val median = results[results.size / 2]
println("$PRINT_REFIX -> average=${average}ms / median=${median}ms")
}
/**
* Used to filter console messages easily
*/
private val PRINT_REFIX = "[TimeTest]"
@olegcherr
Copy link
Author

A simple tool that can help you to measure the performance of your code in Kotlin.

Usage

simpleMeasureTest {
  // your code for the benchmark
}

With additional parameters:

simpleMeasureTest(10000, 5, 5) {
  // your code for the benchmark
}

Output

I/System.out: [TimeTest] -> go
I/System.out: [TimeTest] Warming 1 of 2
I/System.out: [TimeTest] Warming 2 of 2
I/System.out: [TimeTest] 770ms
I/System.out: [TimeTest] 784ms
I/System.out: [TimeTest] 788ms
I/System.out: [TimeTest] 881ms
I/System.out: [TimeTest] 802ms
I/System.out: [TimeTest] 794ms
I/System.out: [TimeTest] 789ms
I/System.out: [TimeTest] 786ms
I/System.out: [TimeTest] 750ms
I/System.out: [TimeTest] 762ms
I/System.out: [TimeTest] -> average=790ms / median=788ms

To make your life easier, create a new console output filter.
Here is my filter in Android Studio:

image

License

Use this code wherever you like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment