Skip to content

Instantly share code, notes, and snippets.

@nomisRev
Last active December 20, 2022 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nomisRev/7fbe8fd7d000c0f4c3e9641d4778ac88 to your computer and use it in GitHub Desktop.
Save nomisRev/7fbe8fd7d000c0f4c3e9641d4778ac88 to your computer and use it in GitHub Desktop.
TimedDSL
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