How can I get the time it takes a function to test the performance of functions in Kotlin

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.


Measure execution time and also keep the result

Standard Library

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.

Obsolete custom implementation

(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 it's enough to get the time as output on the console:

fun <T> timeIt(message: String = "", block: () -> T): T {
    val start = System.currentTimeMillis()
    val r = block()
    val end = System.currentTimeMillis()
    println("$message: ${end - start} ms")
    return r
}

Usage:

val result = timeIt("note about the code") {
   // do something...
}

Output (example):

note about the code: 1ms