Created
May 15, 2011 06:36
-
-
Save akihiro4chawon/972920 to your computer and use it in GitHub Desktop.
scala.collection.parallel implementations of Akka's Pi Tutorial
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
// 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