Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created October 23, 2011 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/1307572 to your computer and use it in GitHub Desktop.
Save travisbrown/1307572 to your computer and use it in GitHub Desktop.
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 _)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment