Last active
December 20, 2022 10:46
-
-
Save nomisRev/7fbe8fd7d000c0f4c3e9641d4778ac88 to your computer and use it in GitHub Desktop.
TimedDSL
This file contains hidden or 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
import arrow.core.continuations.AtomicRef | |
import arrow.core.continuations.update | |
import kotlin.time.Duration | |
import kotlin.time.ExperimentalTime | |
import kotlin.time.TimedValue | |
import kotlin.time.measureTimedValue | |
@OptIn(ExperimentalTime::class) | |
class TimedDSL { | |
val total: AtomicRef<Duration> = AtomicRef(Duration.ZERO) | |
inline fun <A> time(block: () -> A): A { | |
val (a, duration) = measureTimedValue(block) | |
total.update { it + duration } | |
return a | |
} | |
} | |
/** | |
* time { | |
* time { delay(1.seconds) } | |
* println("Some other code").also { delay(10.seconds) } | |
* time { delay(300.milliseconds) } | |
* "final result" | |
* } // TimedValue("final result", 1.3 seconds) | |
*/ | |
@OptIn(ExperimentalTime::class) | |
inline fun <A> time(block: TimedDSL.() -> A): TimedValue<A> { | |
val timed = TimedDSL() | |
val a = timed.block() | |
return TimedValue(a, timed.total.get()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment