Created
May 24, 2012 02:00
-
-
Save ybiquitous/2779016 to your computer and use it in GitHub Desktop.
Scala 末尾再帰とループとfoldのベンチマーク
This file contains 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 scala.testing.Benchmark | |
import scala.annotation.tailrec | |
trait Times { | |
def times(elems: Seq[BigInt]): BigInt | |
} | |
abstract class Bench extends Times with Benchmark { | |
val fixture = BigInt(1) to BigInt(2000) | |
def run() { times(fixture) } | |
} | |
object Tail extends Bench { | |
def times(elems: Seq[BigInt]): BigInt = { | |
@tailrec | |
def worker(b: BigInt, s: Seq[BigInt]): BigInt = { | |
if (s.isEmpty) b else worker(b * s.head, s.tail) | |
} | |
worker(BigInt(1), elems) | |
} | |
} | |
object Loop extends Bench { | |
def times(elems: Seq[BigInt]): BigInt = { | |
var res = BigInt(1) | |
elems foreach { res *= _ } | |
res | |
} | |
} | |
object Fold extends Bench { | |
def times(elems: Seq[BigInt]): BigInt = { | |
(BigInt(1) /: elems){ _ * _ } | |
} | |
} | |
object Main { | |
def main(args: Array[String]) { | |
// test | |
test(Tail) | |
test(Loop) | |
test(Fold) | |
// benchmark | |
Tail.main(args) | |
Loop.main(args) | |
Fold.main(args) | |
} | |
def test(t: Times) { | |
assert{ t.times(BigInt(1) to BigInt(0)) == BigInt(1) } | |
assert{ t.times(BigInt(1) to BigInt(1)) == BigInt(1) } | |
assert{ t.times(BigInt(1) to BigInt(2)) == BigInt(2) } | |
assert{ t.times(BigInt(1) to BigInt(3)) == BigInt(6) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment