Wednesday, 20 January 2010

Time This!

As I was going through the exercise of implementing the Fibonacci function in Scala, I had to add some code to measure how long each implementation (naive recursion vs. tail recursion) took. The pattern is quite simple: measure the time at the start of the operation, do some work, measure time again at the end of the operation and log the difference in a user friendly message. Although quite simple, the pattern is quite verbose, and if you use it a lot, it results in a lot of boiler plate. Scala makes life a bit easier by allowing me (and you) to write your own control structures. So I wrote one called timeThis which basically times (in milliseconds or nanoseconds) the execution of the block of code it contains. You use it like this:
And the output looks like this:
Here are some of the Scala features which make this possible:
  • Methods can take functions as parameters: this applies to code blocks.
  • Partially applied functions: you can turn a method of any object into a function that can then be assigned to a variable (and passed around as a parameter).
  • Use a Scala object to store "static" methods.
  • Use Scala import to import an object's methods.
And here is my implementation of timeThis which makes use of the above features. I hope the comments are sufficiently self explanatory.
The code is quite simple, and I mainly wrote it to gain a better understanding of the way Scala handles functions. If you find this interesting, I suggest you have look at StopWatch, an open source library to monitor your JVM applications. It has a ton of interesting features including statistics and nice graphs.


  1. There appears to be a problem with your code snippets, they are not visible.

  2. @David,
    I wrote this a long time ago using syntax highlighter. I've now replaced the code snippets using Gists. Hopefully you can now see the code.