Stopwatch implementation in Scala

Timing method operations can be a labouring task littering the method body with the timing variables (sometimes short-lived as in debug mode). Thankfully we can treat the timing activity as a pass-by-name method argument of our newly defined timing operation:

def timed [T] (f: => T): T = {
 val startTime = System.currentTimeMillis()
 try f finally println(s"Function completed in: ${System.currentTimeMillis() - startTime} ms" )
}
Advertisements

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 )

Google+ photo

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

Connecting to %s