Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created March 27, 2014 11:42
Show Gist options
  • Save davidallsopp/9805707 to your computer and use it in GitHub Desktop.
Save davidallsopp/9805707 to your computer and use it in GitHub Desktop.
Little utility for timing a block of code
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