Skip to content

Instantly share code, notes, and snippets.

@hsienchiaolee
Created February 12, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsienchiaolee/4693128cd94fbfbec22efe7224bf1519 to your computer and use it in GitHub Desktop.
Save hsienchiaolee/4693128cd94fbfbec22efe7224bf1519 to your computer and use it in GitHub Desktop.
Helper function for simple method benchmarking
// Source: https://stackoverflow.com/questions/9160001/how-to-profile-methods-in-scala
def benchmark[R](runs: Int, block: => R) = {
def print_result(s: String, ns: Long) = {
val formatter = java.text.NumberFormat.getIntegerInstance
println("%-16s".format(s) + formatter.format(ns) + " ns")
}
var t0 = System.nanoTime()
var result = block // call-by-name
var t1 = System.nanoTime()
print_result("First Run", (t1 - t0))
var lst = for (i <- 1 to runs) yield {
t0 = System.nanoTime()
result = block // call-by-name
t1 = System.nanoTime()
(t1 - t0).toLong
}
print_result("Max", lst.max)
print_result("Min", lst.min)
print_result("Avg", (lst.sum / lst.length))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment