Skip to content

Instantly share code, notes, and snippets.



Last active May 14, 2020
What would you like to do?

Kotlin Snippets

A tiny collection of Kotlin snippets that I find useful.

Measure Execution time

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")

Retry mechanism with exponential backoff

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) {
            timeout = (timeout * 2).coerceAtMost(defaultTimeout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment