Created
March 4, 2019 15:38
-
-
Save monadplus/e7fd6a85414434c0b8f302cf68015375 to your computer and use it in GitHub Desktop.
Record Execution Time with WriterT
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
// From https://www.softwaretalks.io/v/4720/lambda-world-2018-boring-use-cases-for-exciting-types-itamar-ravid | |
type Timed[A] = WriterT[Id, Map[String, FiniteDuration], A] | |
def timed[A](name: String, lazyA: () => A): Timed[A] = | |
WriterT[Id, Map[String, FiniteDuration], A] { | |
timed(lazyA).leftMap(duration => Map(name -> duration)) | |
} | |
trait TimedOps { | |
def logMetric(): Unit | |
} | |
trait ToTimedOps { | |
implicit def toTimedOps[A](target: Timed[A])(implicit logger: Logger): TimedOps = | |
new TimedOps { | |
override def logMetric(): Unit = { | |
val (records, _) = target.run | |
records.foreach { case (name, d) => logger.info(s"Execution time of $name $d")} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment