Skip to content

Instantly share code, notes, and snippets.

@urcadox
Created January 5, 2022 14:42
Show Gist options
  • Save urcadox/108c9865ac0f7ca6208b96cc76f24024 to your computer and use it in GitHub Desktop.
Save urcadox/108c9865ac0f7ca6208b96cc76f24024 to your computer and use it in GitHub Desktop.
Tool to print future timing in Scala
object StuffUsingTimedFutures {
def slowFuture(): Unit = {
val future = Future {
Thread.sleep(1000)
}
TimedFuture(future).printTime("foo")
}
}
package utils
import scala.concurrent.{Future, ExecutionContext}
class TimedFuture[T](future: => Future[T])(implicit ec: ExecutionContext) {
private val start = System.nanoTime()
def printTime(name: String): Future[T] = {
future andThen {
case _ => {
val elapsed = System.nanoTime() - start
val elapsedInMilliseconds = BigDecimal(elapsed / 1_000_000.0).setScale(4, BigDecimal.RoundingMode.HALF_UP)
println(s"$name took $elapsedInMilliseconds ms to complete")
}
}
}
}
object TimedFuture {
def apply[T](future: => Future[T])(implicit ec: ExecutionContext) = new TimedFuture(future)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment