You have a couple of "code smells" in there, which suggest that a better, shinier design is probably just around the corner:
- You're using a mutable variable, var instead of val
- timeit works exclusively by side effects, it modifies state outside of the function and successive calls with the same input can have different results.
seq
is slightly risky as a variable name, it's far too close to the (very common & popular) Seq
type from the standard library.
So going back to first principles, how else might the same results be achieved in a more "idiomatic" style? Starting with the original design (as I understand it):
- the first call to
timeit(seq,comment)
just notes the current time
- subsequent calls with the same value of
seq
println the time elapsed since the previous call
Basically, you just want to time how long a block of code takes to run. If there was a way to pass a "block of code" to a function, then maybe, just maybe... Fortunately, scala can do this, just use a by-name param:
def timeit(block: => Unit) : Long = {
val start = System.currentTimeMillis
block
System.currentTimeMillis - start
}
Just check out that block
parameter, it looks a bit like a function with no arguments, that's how by-name params are written. The last expression of the function System.currentTimeMillis - start
is used as the return value.
By wrapping the parameter list in {} braces instead of () parentheses, you can make it look like a built-in control structure, and use it like this:
val duration = timeit {
do stuff here
more stuff
do other stuff
}
println("setup time:" + duration + "ms")
Alternatively, you can push the println behaviour back into the timeit function, but that makes life harder if you later want to reuse it for timing something without printing it to the console:
def timeit(description: String)(block: => Unit) : Unit = {
val start = System.currentTimeMillis
block
val duration System.currentTimeMillis - start
println(description + " took " + duration + "ms")
}
This is another trick, multiple parameter blocks. It allows you to use parentheses for the first block, and braces for the second:
timeit("setup") {
do stuff here
more stuff
do other stuff
}
// will print "setup took XXXms"
Of course, there's a million other variants you can make on this pattern, with varying degrees of sophistication/complexity, but it should be enough to get you started...