Created
November 28, 2011 16:25
-
-
Save j5ik2o/1400970 to your computer and use it in GitHub Desktop.
パラレルコレクションのデモ
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.collection.immutable.NumericRange | |
object Util { | |
// nまでの階乗を計算するメソッド | |
def fac(n: BigInt) = | |
NumericRange(BigInt(1), n, BigInt(1)). | |
foldLeft(BigInt(1)){(cur, next) => | |
cur * next | |
} | |
} | |
import scala.testing.Benchmark | |
import Util._ | |
// 通常のコレクション版 | |
object FactSerial extends Benchmark { | |
def run { | |
// mapメソッドは要素型を変換する | |
// 1から2000までの階乗計算を行う | |
(1 to 2000).map{ x => fac(x) } | |
} | |
} | |
// パラレルコレクション版 | |
object FactParallel extends Benchmark { | |
def run { | |
// parメソッドを使う | |
(1 to 2000).par.map{ x => fac(x) } | |
} | |
} | |
object Bench{ | |
// エントリポイント | |
def main(args: Array[String]) { | |
val mode = args(0) | |
val tryCount = args(1).toInt | |
if ("N" == mode){ | |
log("Normal"){ | |
FactSerial.runBenchmark(tryCount) | |
} | |
}else if ("P" == mode){ | |
log("Parallel"){ | |
FactParallel.runBenchmark(tryCount) | |
} | |
} | |
} | |
// ログ表示を行うメソッド | |
def log(msg: String)(f: => List[Long]){ | |
println("--- %s ---".format(msg)) | |
val result = avgMaxMin(noiseCut(f)) | |
println("n = %d\n%6.2f(%4.0f-%4.0f)". | |
format(result._1, result._2, result._3, result._4)) | |
} | |
// 最大値と最小値を除去するメソッド | |
def noiseCut(result: List[Long]) = { | |
val min = result.min | |
val max = result.max | |
result.filterNot{ x => x == min || x == max } | |
} | |
// 平均、最小、最大をタプルで返すメソッド | |
def avgMaxMin(result: List[Long]) = { | |
(result.size, BigDecimal(result.sum)/BigDecimal(result.size), | |
BigDecimal(result.min), BigDecimal(result.max)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment