Scala makes things expressive – timing

29Jun09

How often have you done something like this? -

public Result calculate() {
  long start = System.currentTimeMillis();
  Result myResult = doSomethingLongAndComplex();
  log.debug("Crunching took " + (System.currentTimeMillis() - start) + "ms.");
  return myResult;
}

It’s kind of ugly when you do it a few times and it does clutter the code. The need for defining an explicit myResult var is even more annoying. So, today, I added this to my Logging trait (see earlier post):

def timed[R](blockName:String)(block:=>R) = {
  val start = System.currentTimeMillis
  val result = block
  debug("Block (" + blockName + ") took " + (System.currentTimeMillis - start) + "ms.")
  result
}

What’s the big deal? – I hear you ask… The big deal is that I can say this in my code now:

def calculation : Result = {
  timed[Result]("calculate something") {
    doSomethingLongAndComplex
  }
}

And at the end of this block I’ll have the time in the log. Also, this block actually returns Result, so this could be the whole body of my function.



No Responses Yet to “Scala makes things expressive – timing”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.