Skip to content

Instantly share code, notes, and snippets.

@paulmr
Created June 14, 2021 14:38
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 paulmr/2d2f3acf4e7033fe7e65e8114324b2c2 to your computer and use it in GitHub Desktop.
Save paulmr/2d2f3acf4e7033fe7e65e8114324b2c2 to your computer and use it in GitHub Desktop.
time a scala expression's execution
// e.g., from the repl:
// scala> :load timer.scala
// [...]
// scala> timed(Thread.sleep(1000))
// took 1001606189ns (1001ms)
def timed[T](block: => T): T = {
import java.time.Duration
val startTime = System.nanoTime()
val res = block
val endTime = System.nanoTime()
val took = Duration.ofNanos(endTime - startTime)
println(s"took ${took.toNanos}ns (${took.toMillis}ms)")
res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment