Kevin K
02/25/2021, 4:30 AMmeasureTimedValue
method to measure time while still allowing capture of the code block result. I found it a little cumbersome to work with the TimedValue
result though; it isn't very fluent. I made this extension function to help, and I was thinking maybe it would be a good addition to the API?
@ExperimentalTime
inline fun <T> TimedValue<T>.capture(block: (Duration) -> Unit): T {
block(duration)
return value
}
@ExperimentalTime
fun main() {
// Without the capture function
val (result, duration) = measureTimedValue {
Thread.sleep(500)
"foobar"
}
println("Duration: $duration")
println("Result: $result")
// With the capture function
measureTimedValue {
Thread.sleep(500)
"foobar"
}.capture {
println("Duration: $it")
}.also {
println("Result: $it")
}
}
(P.S. - I'm not very satisfied with the name capture
...feel like there's definitely a better word to use, just can't think of it)Ruckus
02/25/2021, 4:34 AMKevin K
02/25/2021, 4:37 AMilya.gorbunov
02/25/2021, 4:47 AMmeasureTimedValue
is a top-level function, so it already breaks method chains.Kevin K
02/25/2021, 4:51 AMlet
, but then ofc breaking the chain inside the let
isn't a problemKevin K
02/25/2021, 4:53 AMreturn "foo".toUpperCase()
.let {
measureTimedValue {
it.replace("F", "B")
}.capture {
println(it)
}
}
.toLowerCase()
Kevin K
02/25/2021, 4:54 AMmap
/ filter
when working with sequencesilya.gorbunov
02/25/2021, 5:04 AMmeasureTimedValue {
it.replace("F", "B")
}.also {
println(it.duration)
}.value
Kevin K
02/25/2021, 5:09 AMedrd
02/25/2021, 12:14 PMmeasureTimedValue {
Thread.sleep(500)
"foobar"
}.also { (result, duration) ->
println(duration)
}