measureTime

inline fun measureTime(block: () -> Unit): Duration(source)

Executes the given function block and returns the duration of the elapsed time interval.

The elapsed time is measured with TimeSource.Monotonic which is the most precise available time source on the platform.

Since Kotlin

1.9

Samples

import kotlin.test.Test
import kotlin.time.Duration.Companion.seconds
import kotlin.time.*

fun main() { 
   //sampleStart 
   fun slowFunction(): Unit = Thread.sleep(1000L)
val elapsed = measureTime {
    slowFunction()
}
println("Time elapsed: ${elapsed.inWholeMilliseconds} milliseconds ($elapsed)") 
   //sampleEnd
}

inline fun TimeSource.measureTime(block: () -> Unit): Duration(source)

Executes the given function block and returns the duration of the elapsed time interval.

The elapsed time is measured with the specified this TimeSource instance.

Since Kotlin

1.9

Samples

import kotlin.test.Test
import kotlin.time.Duration.Companion.seconds
import kotlin.time.*

fun main() { 
   //sampleStart 
   val testSource = TestTimeSource()
val elapsed = testSource.measureTime {
    println("Pretending this function executes 10 seconds")
    testSource += 10.seconds
}
println("Time elapsed: ${elapsed.inWholeMilliseconds} milliseconds ($elapsed)") 
   //sampleEnd
}

Executes the given function block and returns the duration of the elapsed time interval.

The elapsed time is measured with the specified this TimeSource.Monotonic instance. The explicit instance allows using non-boxed version of TimeSource.Monotonic.ValueTimeMark and, optionally, be more explicit about the intent.

Since Kotlin

1.9

Samples

import kotlin.test.Test
import kotlin.time.Duration.Companion.seconds
import kotlin.time.*

fun main() { 
   //sampleStart 
   fun slowFunction(): Unit = Thread.sleep(1000L)
val elapsed = TimeSource.Monotonic.measureTime {
    slowFunction()
}
println("Time elapsed: ${elapsed.inWholeMilliseconds} milliseconds ($elapsed)") 
   //sampleEnd
}