To use for example from the scala console in order to quickly get a function response time :


def now=System.currentTimeMillis
def duration[T](proc : =>T) = {
val started = now
val result = proc
(now - started, result)
}


Use case : Ordering a 100000 list of integer, built like as follow :


val lst = (1 to 1000000).reverse.toList


Get / view response time :


duration {lst.sortBy{x=>x}}


Or store the response time result :


val (responsetime, _) = duration {lst.sortBy{x=>x}}


Since we're using a Java Virtual Machine, one measurement is not enough, we must make several iterations in order for the jvm to reach its steady state, and masks GarbageCollector border side effects on response times. We can use such approach :


def howlong[T](proc : =>T, howmany:Long=5) {
val durs = (1L to howmany) map {i =>
val (dur,_) = duration {proc}
dur
}
println("Duration : avg=%d min=%d max=%d all=%s".
format(durs.sum/durs.size, durs.min, durs.max, durs))
}


It gives, in milliseconds :


scala> howlong {lst.sortBy{x=>x}}
Duration : avg=670 min=524 max=903 all=Vector(816, 573, 524, 903, 534)


CONTEXT : Linux Gentoo / Scala 2.9.0 / Java 1.6.0_26