Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure time of a statement in scala console?

Tags:

regex

scala

I'm using Scala to measure performance of regex engine of java. The regexp below executes in around 3 seconds but yet I'm not able to measure it using System.currentTimeMillis. (the last expression returns 0)

scala> val b = System.currentTimeMillis; val v = new Regex("(x+)+y").findAllIn("x"*25); b-System.currentTimeMillis b: Long = 1330787275629 v: scala.util.matching.Regex.MatchIterator = empty iterator res18: Long = 0 

Do you now why the last returned value is 0, and not the amount of ms that scala spend on executing the regexp?

like image 723
Piotr Czapla Avatar asked Mar 03 '12 15:03

Piotr Czapla


1 Answers

The unexplained duration comes from the REPL calling toString on the iterator returned from findAllIn. This in turn calls Regex.MatchIterator#hasNext, which triggers the search.

scala> def time[A](a: => A) = {      |   val now = System.nanoTime      |   val result = a      |   val micros = (System.nanoTime - now) / 1000      |   println("%d microseconds".format(micros))      |   result      | } time: [A](a: => A)A  scala> :power ** Power User mode enabled - BEEP WHIR GYVE ** ** :phase has been set to 'typer'.          ** ** scala.tools.nsc._ has been imported      ** ** global._, definitions._ also imported    ** ** Try  :help, :vals, power.<tab>           **  scala> :wrap time Set wrapper to 'time'  scala> new Regex("(x+)+y").findAllIn("x"*25).toString 3000737 microseconds res19: String = empty iterator  scala> {new Regex("(x+)+y").findAllIn("x"*25); 0} 582 microseconds res20: Int = 0 
like image 52
retronym Avatar answered Oct 01 '22 16:10

retronym