Last active
March 7, 2021 21:49
-
-
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/
This file contains 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 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