Hey all, does anyone have a good suggestion on how...
# getting-started
a
Hey all, does anyone have a good suggestion on how to measure execution time and log the duration in a finally block? Is this only achievable explicitly like the following?
Copy code
val startTime = System.currentTimeMillis()
try {
    <some code>
} finally {
    val duration = Duration.ofMillis(System.currentTimeMillis() - startTime)
}
Thanks in advance ✌️
s
If you want to keep the
finally
block you can simplify it a bit like this:
Copy code
val start = TimeSource.Monotonic.markNow()
try {
  TODO("Some code")
} finally {
  println("Time taken: ${start.elapsedNow()}")
}
thank you color 1
h
Or use the TimeSource directly:
Copy code
val start = TimeSource.Monotonic.markNow()
        try {
            
        } finally {
            val duration = start.elapsedNow()
        }
s
🫰
k
Another possibility, though I prefer the more explicit try-finally suggestions above:
Copy code
val (result, duration) = measureTimedValue {
    runCatching {
        ...
    }
}
println(duration)
println(result.getOrThrow())
🆒 1
☝️ 1
a
Thanks guys! Will go with the Timesource approach!