File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
src/07-multiprocessing/cpu_attempt Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ import datetime
2
+ import math
3
+ import multiprocessing
4
+
5
+
6
+ def main ():
7
+ do_math (1 )
8
+
9
+ t0 = datetime .datetime .now ()
10
+
11
+ print ("Doing math on {:,} processors." .format (multiprocessing .cpu_count ()))
12
+
13
+ pool = multiprocessing .Pool ()
14
+ processor_count = multiprocessing .cpu_count ()
15
+ tasks = []
16
+ for n in range (1 , processor_count + 1 ):
17
+ task = pool .apply_async (do_math , (30_000_000 * (n - 1 ) / processor_count ,
18
+ 30_000_000 * n / processor_count ))
19
+ tasks .append (task )
20
+
21
+ pool .close ()
22
+ pool .join ()
23
+
24
+ dt = datetime .datetime .now () - t0
25
+ print ("Done in {:,.2f} sec." .format (dt .total_seconds ()))
26
+ print ("Our results: " )
27
+ for t in tasks :
28
+ print (t .get ())
29
+
30
+
31
+ def do_math (start = 0 , num = 10 ):
32
+ pos = start
33
+ k_sq = 1000 * 1000
34
+ ave = 0
35
+ while pos < num :
36
+ pos += 1
37
+ val = math .sqrt ((pos - k_sq ) * (pos - k_sq ))
38
+ ave += val / num
39
+
40
+ return int (ave )
41
+
42
+
43
+ if __name__ == '__main__' :
44
+ main ()
You can’t perform that action at this time.
0 commit comments