Created
March 27, 2014 11:42
-
-
Save davidallsopp/9805707 to your computer and use it in GitHub Desktop.
Little utility for timing a block of code
This file contains hidden or 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 Timer { | |
/** Time a block of code, print the duration in millis, and return the value of the block*/ | |
def time[A](f: => A): A = time2(f) match { | |
case (a, nanos) => | |
println("time: " + nanos / 1000000L + "ms") | |
a | |
} | |
/** Time a block of code, return a tuple of the value of the block and the duration in nanos */ | |
def time2[A](f: => A): (A, Long) = { | |
val s = System.nanoTime | |
val ret = f | |
(ret, System.nanoTime - s) | |
} | |
/** Time a block of code, and return just the duration in nanos*/ | |
def nanos(f: => Any): Long = time2(f)._2 | |
def micros[A](f: => A): Long = nanos(f) / 1000L | |
def millis[A](f: => A): Long = nanos(f) / 1000000L | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment