Skip to content

Instantly share code, notes, and snippets.

@asflierl
Created January 2, 2011 23:55
Show Gist options
  • Save asflierl/762943 to your computer and use it in GitHub Desktop.
Save asflierl/762943 to your computer and use it in GitHub Desktop.
benchmark for specialized numeric abstraction
trait Plus1[A] {
def plus(a: A, b: A): A
}
object Plus1 {
implicit val LongPlus1 = new Plus1[Long] {
def plus(a: Long, b: Long) = a + b
}
}
trait Plus2[@specialized A] {
def plus(a: A, b: A): A
}
object Plus2 {
implicit val LongPlus2 = new Plus2[Long] {
def plus(a: Long, b: Long) = a + b
}
}
object Main {
val impls = List(("direct", directImpl _),
("generic", genericImpl _),
("generic + specialized", genericSpecializedImpl _))
def main(args: Array[String]): Unit = {
impls foreach (_._2.apply) // warmup
impls foreach (t => time((t._1, t._2.apply)))
}
def directImpl = {
var s = 0L
var i = 0L
while (i < 100000000L) {
s = s + i
i += 1L
}
s
}
def genericImpl = {
var s = 0L
var i = 0L
while (i < 100000000L) {
s = f(s, i)
i += 1L
}
s
}
def f[A](a: A, b: A)(implicit op: Plus1[A]): A = op.plus(a, b)
def genericSpecializedImpl = {
var s = 0L
var i = 0L
while (i < 100000000L) {
s = g(s, i)
i += 1L
}
s
}
// it's important to specialize this method, too, of course
def g[@specialized A](a: A, b: A)(implicit op: Plus2[A]): A = op.plus(a, b)
def time[A](x: => (String, A)): A = {
val before = System.currentTimeMillis
val r = x
val expired = System.currentTimeMillis - before
println("%s implementation took %d ms and resulted in %d" format (r._1, expired, r._2))
r._2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment