2
0
Fork 0
mirror of https://github.com/MartinThoma/LaTeX-examples.git synced 2025-04-26 06:48:04 +02:00
LaTeX-examples/documents/Programmierparadigmen/scripts/scala/erasthostenes-parallel.scala
Martin Thoma b18561fc54 misc
2014-03-24 23:25:10 +01:00

35 lines
No EOL
1.4 KiB
Scala

import scala.actors.Futures._
/** @author Axel Busch */
object EratosthenesFutures {
def parallel(end : Int, threads: Int) : Array[Boolean] = {
val sieve = Array.fill[Boolean](end+1)(true)
for (i <- 2 to scala.math.sqrt(end).toInt) {
if (sieve(i)) {
val nextComposite = i*i
val compositesPerThread = (end-nextComposite+1)/(threads*i)
val tasks = for (t <- 0 until threads) yield future {
val begin = nextComposite + t * i *
compositesPerThread
val finish = if (t+1 == threads) end
else nextComposite + (t+1) * i *
compositesPerThread
assert (begin % i == 0)
for (composite <- begin to finish by i) {
sieve(composite) = false
}
}
awaitAll(20000L, tasks: _*);
}
}
sieve
}
def main(args: Array[String]) = {
val end = 100000000
for (threads <- List(1,2,4,8)) {
val startTime = System.currentTimeMillis();
parallel(end,threads);
val endTime = System.currentTimeMillis();
println(threads + " thread: " + (endTime - startTime) + " ms");
}
}
}