Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created March 4, 2019 15:38
Show Gist options
  • Save monadplus/e7fd6a85414434c0b8f302cf68015375 to your computer and use it in GitHub Desktop.
Save monadplus/e7fd6a85414434c0b8f302cf68015375 to your computer and use it in GitHub Desktop.
Record Execution Time with WriterT
// 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