Created
April 7, 2011 21:11
-
-
Save dbyrne/908732 to your computer and use it in GitHub Desktop.
Micro-benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collection.breakOut | |
val s = (0 until 1000000).toSet | |
def func(i: Int) = "" + i + i | |
Profiling.timed(Profiling.printTime("Jesper (original): ")){ | |
(s map { i => i -> func(i) }).toMap | |
} | |
Profiling.timed(Profiling.printTime("Jesper (improved): ")){ | |
(s.view.map { i => i -> func(i) }).toMap | |
} | |
Profiling.timed(Profiling.printTime("dbyrne: ")){ | |
val func2 = (r: Map[Int,String], i: Int) => r + (i -> func(i)) | |
s.foldLeft(Map.empty[Int,String])(func2) | |
} | |
Profiling.timed(Profiling.printTime("Rex Kerr: ")){ | |
Map() ++ s.view.map(i => i -> func(i)) | |
} | |
Profiling.timed(Profiling.printTime("Eastsun: ")){ | |
val map: Map[Int,String] = s.map(i => i -> func(i))(breakOut) | |
} | |
object Profiling { | |
def timed[T](report: Long=>Unit)(body: =>T) = { | |
val start = System.nanoTime | |
val r = body | |
report(System.nanoTime - start) | |
r | |
} | |
private val timeUnits = List("ns", "us", "ms", "s") | |
def formatTime(delta:Long) = { | |
def formatTime(v:Long, units:List[String], tail:List[String]):List[String] = { | |
def makeTail(what:Long) = (what + units.head) :: tail | |
if(!units.tail.isEmpty && v >= 1000) | |
formatTime(v / 1000, units.tail, makeTail(v % 1000)) | |
else | |
makeTail(v) | |
} | |
formatTime(delta, timeUnits, Nil).mkString(" ") | |
} | |
def printTime(msg:String) = (delta:Long) => { | |
println(msg + formatTime(delta)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment