Created
September 10, 2011 15:39
-
-
Save schmmd/1208447 to your computer and use it in GitHub Desktop.
scala-timing-helpers
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
object Timing { | |
/** Return a tuple, where the first part is the milliseconds | |
* taken and the second part is the result of the block | |
* execution. */ | |
def time[R](block: =>R): (Long, R) = { | |
val start = System.currentTimeMillis | |
val result = block | |
(System.currentTimeMillis - start, result) | |
} | |
/** Execute the block and pass the time taken to the handler. */ | |
def time[R](block: =>R, handler: Long=>Any): R = { | |
val (ms, result) = time(block) | |
handler(ms) | |
result | |
} | |
/** Execute the command and print the time taken. */ | |
def printTime[R](block: =>R) { | |
time(block, println) | |
} | |
/** A class to store timing statistics. */ | |
class Stats(val total: Long, val max: Long, val min: Long, val avg: Long) { | |
override def toString = | |
"total: " + total + "ms, min: " + min + | |
"ms, max: " + max + "ms, avg: " + avg + "ms" | |
} | |
/** Execute the blocks and report statistics about the time taken. */ | |
def speedTest(executions: List[() => Any]) { | |
val times = executions.map(e => time({ e () })._1) | |
val total = times.reduce(_+_) | |
val max = times.reduce(math.max(_, _)) | |
val min = times.reduce(math.min(_, _)) | |
val avg = total / executions.size | |
new Stats(total, max, min, avg) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. Would like to try out your cool Timing.scala object. can you provide an example of how to wrap a function with the speedTest?