Debian Codegraph @

libphobos/testsuite/libphobos.phobos/std_parallelism.d

raw
1 @system unittest
2 {
3 import std.parallelism;
4
5 import std.algorithm.iteration : map;
6 import std.math.operations : isClose;
7 import std.parallelism : taskPool;
8 import std.range : iota;
9
10 // Parallel reduce can be combined with
11 // std.algorithm.iteration.map to interesting effect.
12 // The following example (thanks to Russel Winder)
13 // calculates pi by quadrature using
14 // std.algorithm.map and TaskPool.reduce.
15 // getTerm is evaluated in parallel as needed by
16 // TaskPool.reduce.
17 //
18 // Timings on an Intel i5-3450 quad core machine
19 // for n = 1_000_000_000:
20 //
21 // TaskPool.reduce: 1.067 s
22 // std.algorithm.reduce: 4.011 s
23
24 enum n = 1_000_000;
25 enum delta = 1.0 / n;
26
27 alias getTerm = (int i)
28 {
29 immutable x = ( i - 0.5 ) * delta;
30 return delta / ( 1.0 + x * x ) ;
31 };
32
33 immutable pi = 4.0 * taskPool.reduce!"a + b"(n.iota.map!getTerm);
34
35 assert(pi.isClose(3.14159, 1e-5));
36 }
37