Scala snippet of the day

The following is useful for benchmarking code from inside the REPL:

def timed(op: => Unit) = {
  val start = System.nanoTime
  (System.nanoTime - start) / 1e9

Then you can use it like this:

scala> timed { Thread.sleep(5000) }
res0: Double = 5.010083526

That's syntactic sugar for an anonymous function definition and a call of timed. If a function takes only a single parameter you can pass it inside { }, so if we wrote that out longhand it would be:

scala> def fn = Thread.sleep(5000)
fn: Unit

scala> timed(fn)
res0: Double = 5.010088248

The other neat bit is the use of Scala's pass-by-name mechanism to pass the op parameter. That's the funny-looking op: => Unit argument list to timed. Normally Scala uses by-value parameters, i.e. the line timed(fn) would result in the evaluation of fn, and then passing the returned value (in this case, nothing) into timed. However by using pass-by-name, the evaluation of fn takes place inside timed, and by wrapping it inside timing instrumentation we can time how long op takes to execute.

Tags : ,
Categories : Web, Tech