craigrussell

Technical blog from Craig Russell.

 

Kotlin — Measure and Execute a block of code

stock image of a white kitchen timer

Overview

This post illustrates a utility function which executes a block of code. It also measures how long it took to execute, and logs the duration.

This is useful for generating crude benchmarks of operations so you can see roughly how long a block of code takes to execute. It’s not scientific, but sometimes it’s enough to make decisions on where bottlenecks might lie.

It records the start time, executes the function and prints out the time it took to execute.

Measure and Execute

inline fun <T> measureExecution(logMessage: String, logLevel: Int = Log.DEBUG, function: () -> T): T {
    val startTime = System.nanoTime()
    return function.invoke().also {
        val difference = System.nanoTime() - startTime
        Timber.log(logLevel, "$logMessage; took ${TimeUnit.NANOSECONDS.toMillis(difference)}ms")
    }
}

Usage

For the simplest usage case, call the measureExecution function passing in the log statement to accompany the measurement. For example:

measureExecution("Finished doing work") {
  foo.doSomeWork()
}

This will output Finished doing work; took 123ms at DEBUG log level. If you wanted to log to a different log level, and perhaps return a value, that’s cool too.

val result = measureExecution("Finished doing work", Log.INFO) {
  foo.doSomeWork()
  return foo.getResult()
}

You don’t even need to specify the type; the compiler will figure it out 👌

Image Attribution: Marcelo Leal on Unsplash

Home