Skip to content

Instantly share code, notes, and snippets.

@akihiro4chawon
Created May 15, 2011 06:36
Show Gist options
  • Save akihiro4chawon/972920 to your computer and use it in GitHub Desktop.
Save akihiro4chawon/972920 to your computer and use it in GitHub Desktop.
scala.collection.parallel implementations of Akka's Pi Tutorial
// Akka's Pi Tutorial implemented with scala.collection.parallel
object PiParallel extends App {
import scala.collection.GenSeq
val seqRng = Range(0, 10000 * 10000).view
val parRng = Range(0, 10000 * 10000).par.view
def calculatePi(rng: GenSeq[Int]): Double =
rng.map{i => 4.0 * (1 - (i % 2) * 2) / (2 * i + 1)}.sum;
def calculatePiInline: Double = {
var sum = 0.0
var i = 0;
while (i < 10000 * 10000) {
sum += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1)
i += 1
}
sum
}
println("collection.parallel.availableProcessors == "+collection.parallel.availableProcessors)
timeKeep(calculatePi(seqRng), "Sequential:")
timeKeep(calculatePi(parRng), "Parallel:")
timeKeep(calculatePiInline, "Inline(Seq):")
def timeKeep[A <: AnyRef](calcPi: => Double, msg: String) {
println(msg)
val t1 = System.nanoTime
val pi = calcPi
val t2 = System.nanoTime
println(
"\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis"
.format(pi, (t2 - t1) / 1000000))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment