Skip to content

Instantly share code, notes, and snippets.

@sphrak
Last active May 14, 2020 18:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sphrak/3da47dccc946c23b2fc310c95619d1d5 to your computer and use it in GitHub Desktop.
kotlin-snippets

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