Created
January 5, 2022 14:42
-
-
Save urcadox/108c9865ac0f7ca6208b96cc76f24024 to your computer and use it in GitHub Desktop.
Tool to print future timing in Scala
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
object StuffUsingTimedFutures { | |
def slowFuture(): Unit = { | |
val future = Future { | |
Thread.sleep(1000) | |
} | |
TimedFuture(future).printTime("foo") | |
} | |
} |
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
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