44
55import multiprocessing as mp
66
7- def get_data_parts (N ,nb_processes ):
7+ def get_data_parts (N , nb_processes ):
88 # Data is composed of as many sub-lists as there are processes.
99 data = [ [] for i in range (nb_processes )]
1010
1111 for i in range (N ):
12- data [ i % (nb_processes ) ].append ( i )
13-
14- ## Here, the trick is that we use the % operator.
15- ## For instance for 2 processes:
16- ## * If i is 3, then i%2 == 1 -> goes to sublist 1.
17- ## * If i is 4, then i%2 == 0 -> goes to sublist 0.
12+ # Here, the trick is that we use the % operator.
13+ # For instance for 2 processes:
14+ # * If i is 3, then i % 2 == 1 -> goes to sublist 1.
15+ # * If i is 4, then i % 2 == 0 -> goes to sublist 0.
16+ data [i % nb_processes ].append (i )
1817 return data
1918
2019# Let's test it out: say we have 10 points, and 2 processes.
@@ -24,29 +23,29 @@ def get_data_parts(N,nb_processes):
2423print (data_parts )
2524
2625# Then the task is to apply `f2` to a set of points:
27- def f2 (i , a , dx ):
26+ def f2 (i , a , dx ):
2827 x = a + i * dx
2928 return x ** 2 - x
3029
31- def task (data , a , dx ):
30+ def task (data , a , dx ):
3231 s = 0
3332 for d in data :
34- s += f2 (d , a , dx )
35- return s * dx
33+ s += f2 (d , a , dx )
34+ return s * dx
3635
37- #let 's work outside the function and focus on the main loop:
36+ # Let 's work outside the function and focus on the main loop:
3837a = 0
3938b = 2
40- N = 100 #2 * 10**7
39+ N = 100 #2 * 10**7
4140dx = (b - a ) / N
4241
4342data_parts = get_data_parts (N , 2 )
4443
4544# Test it on our test data.
46- S1 , S2 = task (data_parts [0 ],a , dx ), task (data_parts [1 ],a , dx )
47- print ("data parts results:" ,S1 , S2 )
48- # of course at the end you want to sum
49- print ("final result:" , S1 + S2 )
45+ S1 , S2 = task (data_parts [0 ], a , dx ), task (data_parts [1 ], a , dx )
46+ print ("data parts results:" , S1 , S2 )
47+ # of course at the end you want to sum:
48+ print ("final result:" , S1 + S2 )
5049
5150# Now, to be applied with map, we will make a specific version of the task
5251# with a and dx fixed
0 commit comments