Skip to content

Instantly share code, notes, and snippets.

@kafecho
Created March 24, 2013 16:30
Show Gist options
  • Save kafecho/5232557 to your computer and use it in GitHub Desktop.
Save kafecho/5232557 to your computer and use it in GitHub Desktop.
timeThis implementation
trait TimeUnit
case object msecs extends TimeUnit
case object nanosecs extends TimeUnit
object Watch{
/* A hashmap to map a time unit to a tuple containing:
* - a description of the time unit in english.
* - a function invoked to measure the time in the given unit
*/
val timeUnits = Map[TimeUnit,Tuple2[String,() => Long]] (
msecs -> ("msecs",System.currentTimeMillis _),
nanosecs -> ("nanosecs", System.nanoTime _)
)
/*
* Execute a block of code and displays how long its execution took.
* The time unit can be set to msecs or nanoseconds by providing the appropriate time unit object as a parameter.
*/
def timeThis(tu : TimeUnit)(block: => Unit){
timeUnits.get(tu) match{
case Some((description,fn)) =>{
// Measure the start time using the appropriate function.
var start = fn()
// Execute the block
block
// Measure the stop time using the appropriate function.
var stop = fn()
println ("It took " + (stop - start) + " " + description + " to execute the operation.")
}
case _ => println ("Unknown time unit " + tu)
}
}
def timeThis( block: => Unit){
timeThis(msecs)(block)
}
}
// Scala import to be able to use methods defined in Watch object.
import Watch._
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment