Skip to content

Instantly share code, notes, and snippets.

@quii
Created August 27, 2014 12:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quii/7323215ec0b5a5ebfbb7 to your computer and use it in GitHub Desktop.
Save quii/7323215ec0b5a5ebfbb7 to your computer and use it in GitHub Desktop.
Timing futures in Scala
import scala.concurrent.Future
object TimingFutures extends App{
import scala.concurrent.ExecutionContext.Implicits.global
def timedFuture[T](future: Future[T]) = {
val start = System.currentTimeMillis()
future.onComplete({
case _ => println(s"Future took ${System.currentTimeMillis() - start} ms")
})
future
}
// I want to be able to measure how long this function would take
def wantToMeasure = Future{
Thread.sleep(500)
"Foo"
}
//I dont want this function to be added to my measurement
def extraOperation(x: String) ={
Thread.sleep(500)
"Bar"
}
// expect ~500 to be printed - even though ive "added" another slow operation to the future
val result1 = timedFuture(wantToMeasure)
result1 map extraOperation
// expect ~1000 to be printed because i am timing a future with 2 long operations
val result2 = timedFuture(wantToMeasure.map(extraOperation))
readLine()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment