Skip to content

Instantly share code, notes, and snippets.

@alexandru
Created December 30, 2015 14:27
Show Gist options
  • Save alexandru/39c124d0b8e7c66dc5c2 to your computer and use it in GitHub Desktop.
Save alexandru/39c124d0b8e7c66dc5c2 to your computer and use it in GitHub Desktop.
import scalaz.concurrent.Task
def benchmark[T](repeat: Int)(callback: => T): Unit = {
var lastResult: Any = null
var total = Duration.Zero
for (i <- 0 until repeat) {
val time = System.nanoTime()
val result = callback
val measured = (System.nanoTime() - time).nanos
total += measured
if (lastResult != result) {
println(s"$i: Result: $result")
lastResult = result
}
println(s"$i: Time: ${measured.toSeconds} seconds ($measured)")
}
println(s"Average: ${(total.toMillis.toDouble / 1000) / repeat} seconds")
}
def sum(n: Int, acc: Long = 0): Task[Long] = {
if (n == 0) Task(acc) else
Task(n).flatMap(x => sum(x-1, acc + x))
}
benchmark(repeat = 10)(sum(30000000).unsafePerformSync)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment