Instantly share code, notes, and snippets.

# travisbrown/FactorialBenchmark.scala Created Oct 23, 2011

Benchmarking for some factorial functions using Caliper
 import org.jscience.mathematics.number.LargeInteger import com.google.caliper.{ Param, SimpleBenchmark } class FactorialBenchmark extends SimpleBenchmark { // Borrowed from https://github.com/sirthias/scala-benchmarking-template. def repeat[@specialized A](reps: Int)(snippet: => A) = { val zero = 0.asInstanceOf[A] var i = 0 var result = zero while (i < reps) { val res = snippet if (res != zero) result = res i = i + 1 } result } def timeBigIntFoldLeft(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).foldLeft(BigInt(1))(_ * _) } def timeBigIntFold(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).fold(BigInt(1))(_ * _) } def timeBigIntReduce(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).reduce(_ * _) } def timeBigIntFoldLeftPar(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).par.foldLeft(BigInt(1))(_ * _) } def timeBigIntFoldPar(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).par.fold(BigInt(1))(_ * _) } def timeBigIntReducePar(reps: Int) = repeat(reps) { (BigInt(1) to BigInt(50000)).par.reduce(_ * _) } def timeLargeIntegerFoldLeft(reps: Int) = repeat(reps) { (1 to 50000).foldLeft(LargeInteger.ONE)(_ times _) } def timeLargeIntegerFold(reps: Int) = repeat(reps) { (1 to 50000).map(LargeInteger.valueOf(_)).fold(LargeInteger.ONE)(_ times _) } def timeLargeIntegerReduce(reps: Int) = repeat(reps) { (1 to 50000).map(LargeInteger.valueOf(_)).reduce(_ times _) } def timeLargeIntegerFoldLeftPar(reps: Int) = repeat(reps) { (1 to 50000).par.foldLeft(LargeInteger.ONE)(_ times _) } def timeLargeIntegerFoldPar(reps: Int) = repeat(reps) { (1 to 50000).map(LargeInteger.valueOf(_)).par.fold(LargeInteger.ONE)(_ times _) } def timeLargeIntegerReducePar(reps: Int) = repeat(reps) { (1 to 50000).map(LargeInteger.valueOf(_)).par.reduce(_ times _) } }