Last active
April 18, 2020 00:34
-
-
Save Telewa/3d490807555133aa6ec01eb8ab1caca8 to your computer and use it in GitHub Desktop.
Neatly show duration of a function execution in kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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