A tiny collection of Kotlin snippets that I find useful.
Keep in mind this is not an end all be all measurement since the jvm has indeterministic garbage collection but it can give you a general idea of whats taking time.
With return value
inline fun <T> measureTimeMillis(
loggingFunction: (Long) -> Unit,
function: () -> T
): T {
val startTime = System.currentTimeMillis()
val result: T = function.invoke()
loggingFunction.invoke(System.currentTimeMillis() - startTime)
return result
}
Without return value:
fun measureTimeInMillis(block: () -> Unit) {
val nanos = meureNanoTime(block)
val millis = TimeUnit.NANOSECONDS.toMillis(nanos)
println("execution time: $millis ms")
}
private suspend fun <T> retry(defaultTimeout: Long = 60_000L, block: suspend () -> T): T {
var timeout: Long = 1000L
while (true) {
try {
return block()
} catch (e: IOException) {
e.printStackTrace()
}
delay(timeout)
timeout = (timeout * 2).coerceAtMost(defaultTimeout)
}
}