-
Notifications
You must be signed in to change notification settings - Fork 2
/
mpi_pi.py
64 lines (51 loc) · 1.63 KB
/
mpi_pi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
mpirun -v -np 3 -machinefile mpi_hosts python mpi_pi.py
"""
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
slice_size = 1000000
total_slices = 50
# This is the master node.
if rank == 0:
pi = 0
slice = 0
process = 1
print size
# Send the first batch of processes to the nodes.
while process < size and slice < total_slices:
comm.send(slice, dest=process, tag=1)
print "Sending slice",slice,"to process",process
slice += 1
process += 1
# Wait for the data to come back
received_processes = 0
while received_processes < total_slices:
pi += comm.recv(source=MPI.ANY_SOURCE, tag=1)
process = comm.recv(source=MPI.ANY_SOURCE, tag=2)
print "Recieved data from process", process
received_processes += 1
if slice < total_slices:
comm.send(slice, dest=process, tag=1)
print "Sending slice",slice,"to process",process
slice += 1
# Send the shutdown signal
for process in range(1,size):
comm.send(-1, dest=process, tag=1)
print "Pi is ", 4.0 * pi
# These are the slave nodes, where rank > 0. They do the real work
else:
while True:
start = comm.recv(source=0, tag=1)
if start == -1: break
i = 0
slice_value = 0
while i < slice_size:
if i%2 == 0:
slice_value += 1.0 / (2*(start*slice_size+i)+1)
else:
slice_value -= 1.0 / (2*(start*slice_size+i)+1)
i += 1
comm.send(slice_value, dest=0, tag=1)
comm.send(rank, dest=0, tag=2)