Skip to content

Commit 2251a84

Browse files
committed
CPU bound operation on threads -- no improvement.
1 parent 77bbf62 commit 2251a84

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/05-threads/cpu_attempt/compute_threaded.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,28 @@
11
import datetime
22
import math
3+
from threading import Thread
4+
import multiprocessing
35

46

57
def main():
68
do_math(1)
79

810
t0 = datetime.datetime.now()
911

10-
do_math(num=30000000)
12+
# do_math(num=30000000)
13+
print("Doing math on {:,} processors.".format(multiprocessing.cpu_count()))
14+
15+
processor_count = multiprocessing.cpu_count()
16+
threads = []
17+
for n in range(1, processor_count + 1):
18+
threads.append(Thread(target=do_math,
19+
args=(30_000_000 * (n - 1) / processor_count,
20+
30_000_000 * n / processor_count),
21+
daemon=True)
22+
)
23+
24+
[t.start() for t in threads]
25+
[t.join() for t in threads]
1126

1227
dt = datetime.datetime.now() - t0
1328
print("Done in {:,.2f} sec.".format(dt.total_seconds()))
@@ -18,7 +33,7 @@ def do_math(start=0, num=10):
1833
k_sq = 1000 * 1000
1934
while pos < num:
2035
pos += 1
21-
dist = math.sqrt((pos - k_sq)*(pos - k_sq))
36+
math.sqrt((pos - k_sq) * (pos - k_sq))
2237

2338

2439
if __name__ == '__main__':

0 commit comments

Comments
 (0)