Skip to content

Instantly share code, notes, and snippets.

@Telewa
Last active April 18, 2020 00:34
Show Gist options
  • Save Telewa/3d490807555133aa6ec01eb8ab1caca8 to your computer and use it in GitHub Desktop.
Save Telewa/3d490807555133aa6ec01eb8ab1caca8 to your computer and use it in GitHub Desktop.
Neatly show duration of a function execution in kotlin
package com.emma.recursion
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit.*
/**
* How to neatly show duration of a function execution in kotlin
*/
fun timer(f: () -> Unit) {
val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val startTime = LocalDateTime.now()
val methodName = f.javaClass.enclosingMethod.name
println("${startTime.format(dateFormat)} => start ($methodName)")
f()
val endTime = LocalDateTime.now()
println(
"${endTime.format(dateFormat)} => end ($methodName), duration: (${MINUTES.between(
startTime,
endTime
)} minutes| ${SECONDS.between(startTime, endTime)} seconds | ${MILLIS.between(
startTime,
endTime
)} millis | ${NANOS.between(startTime, endTime)} nanos)"
)
}
fun printText(text: String) {
println(text)
}
fun main() {
timer {
printText("telewa")
}
timer {
printText("emmanuel")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment