Skip to content

Commit 09af400

Browse files
committed
Final code for multiprocessing chapter.
1 parent 1bfa87f commit 09af400

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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()

0 commit comments

Comments
 (0)