Created
February 12, 2018 21:06
-
-
Save hsienchiaolee/4693128cd94fbfbec22efe7224bf1519 to your computer and use it in GitHub Desktop.
Helper function for simple method benchmarking
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
// 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