Skip to content

Instantly share code, notes, and snippets.

@ScalaWilliam
Last active March 7, 2021 21:49
Show Gist options
  • Save ScalaWilliam/00fe9a2fbd829c3e9a3fcf99eec07e50 to your computer and use it in GitHub Desktop.
Save ScalaWilliam/00fe9a2fbd829c3e9a3fcf99eec07e50 to your computer and use it in GitHub Desktop.
To debug how quickly different resources start up -- hugely important for application start up time. Used in https://www.scala-algorithms.com/
import cats.effect.{IO, Resource}
import io.chrisdavenport.log4cats.SelfAwareStructuredLogger
import java.time.{Duration, Instant}
object ResourceTimer {
implicit class RichResource[A](resource: Resource[IO, A]) {
def measured(
name: String,
)(implicit logger: SelfAwareStructuredLogger[IO]): Resource[IO, A] =
for {
start <- Resource.liftF[IO, Instant](IO.delay(Instant.now()))
allocated <- resource
difference <- Resource.liftF[IO, Duration](
IO.delay(Instant.now()).map(end => Duration.between(start, end)),
)
_ <- Resource.liftF[IO, Unit](logger.info(
s"Resource '${name}' took $difference to start up.",
))
} yield allocated
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment