Last active
December 25, 2015 04:39
-
-
Save gavinking/6918556 to your computer and use it in GitHub Desktop.
Parallel algorithm for π, originally by Russel Winder
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 java.util.concurrent { | |
Callable, | |
ScheduledThreadPoolExecutor | |
} | |
void execute(Integer numberOfTasks) { | |
value n = 1G; // same number of iterations as Java | |
value delta = 1.0 / n; | |
value startTime = process.nanoseconds; | |
value sliceSize = n / numberOfTasks; | |
value executor = ScheduledThreadPoolExecutor(numberOfTasks); | |
class Task(Integer id) satisfies Callable<Float> { | |
shared actual Float call() { | |
value start = 1 + id * sliceSize; | |
value end = (id + 1) * sliceSize; | |
variable value sum = 0.0; | |
for (i in start..end) { | |
value x = (i - 0.5) * delta; | |
sum += 1.0 / (1.0 + x*x); | |
} | |
return sum; | |
} | |
} | |
value futures = [for (i in 0:numberOfTasks) executor.submit(Task(i))]; | |
assert (nonempty futures); | |
value pi = 4.0 * delta * sum { for (f in futures) f.get() }; | |
value elapseTime = (process.nanoseconds - startTime) / 1.0G; | |
outputN("pi_ceylon_futures", pi, n, elapseTime, numberOfTasks); | |
} | |
"Calculate π using quadrature realized with a parallel algorithm using callables, futures and executors." | |
by("Russel Winder") | |
void run() { | |
execute(1); | |
execute(2); | |
execute(8); | |
execute(32); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment