June 2019
Intermediate to advanced
218 pages
5h 19m
English
In earlier chapters on Threads and GPUs, we have encountered code to calculate the value of Pi using the Monte Carlo simulation. As an example of code that can be easily parallelized, let's try to run this over a distributed Julia cluster. First, we define our function to count the number of hits inside the unit circle:
@everywhere function darts_in_circle(N) n = 0 for i in 1:N if rand()^2 + rand()^2 < 1 n += 1 end end return n end
This is then used via pmap to run in parallel on multiple nodes:
function pi_distributed(N, loops) n = sum(pmap((x)->darts_in_circle(N), 1:loops)) 4 * n / (loops * N) end
We also define a serial version to compare timings:
function pi_serial(n) return 4 * darts_in_circle(n) / nend
Timing ...
Read now
Unlock full access