Created
August 27, 2014 12:38
-
-
Save quii/7323215ec0b5a5ebfbb7 to your computer and use it in GitHub Desktop.
Timing futures 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
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