I need to check how long does a function need to run. I have the following functions which address the same task:
mixAnimalsA
fun mixAnimalsA(a1: Animal, a2: Animal) = when (setOf(a1, a2)) { setOf(Animal.OWL, Animal.Leopard) -> Beast.OWLPARD setOf(Animal.ELEPHANT, Animal.BUTTERFLY) -> Beast.BUTTERPHANT else -> throw Exception("Not possible combination") }
mixAnimalsB
fun mixAnimalsB(a1: Animal, a2: Animal) = when (setOf(a1, a2)) { (c1 == Animal.OWL && c2 == Animal.Leopard) || (c2 == Animal.OWL && c1 == Animal.Leopard) -> Beast.OWLPARD (c1 == Animal.ELEPHANT && c2 == Animal.BUTTERFLY) || (c2 == Animal.ELEPHANT && c1 == Animal.BUTTERFLY)-> Beast.BUTTERPHANT else -> throw Exception("Not possible combination") }
Animal
and Beast
are enumerations. How can I measure how long each function takes to run?
The kotlin. time. measureTime(block: () -> Unit) function accepts a block of code as a lambda expression and calculates the elapsed time while executing it. As opposed to measureTimeMillis() and measureNanoTime(), this function returns a kotlin.
let takes the object it is invoked upon as the parameter and returns the result of the lambda expression. Kotlin let is a scoping function wherein the variables declared inside the expression cannot be used outside.
If you're looking for an in-code solution, you can use measureTimeMillis
and measureNanoTime
, like this:
val time = measureTimeMillis { // call your function here }
They return the measured time in milliseconds and nanoseconds, respectively.
The standard library function measureTimedValue
may be used to measure execution time and at the same time capture the result. This tuple of values is being exposed as a TimedValue(value: T, duration: Duration):
@ExperimentalTime fun main() { val (result: String, duration: Duration) = measureTimedValue { operation() } print("Got $result after ${duration.inMilliseconds} ms.") }
Note that this API is experimental and requires explicit opt-in.
(This used to be my answer before the standard lib was extended)
If you want to measure the execution time and also access the measured function's return value afterward, here's a custom solution:
inline fun <R> executeAndMeasureTimeMillis(block: () -> R): Pair<R, Long> { val start = System.currentTimeMillis() val result = block() return result to (System.currentTimeMillis() - start) }
You can call it like this:
val (response, duration) = executeAndMeasureTimeMillis { restTemplate.getForObject<AnyObject>(uri) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With