forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.py
More file actions
33 lines (22 loc) · 770 Bytes
/
example2.py
File metadata and controls
33 lines (22 loc) · 770 Bytes
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
# ch1/example2.py
import concurrent.futures
from timeit import default_timer as timer
# sequential
def f(x):
return x * x - x + 1
start = timer()
result = 3
for i in range(20):
result = f(result)
print('Result is very large. Only printing the last 5 digits:', result % 100000)
print('Sequential took: %.2f seconds.' % (timer() - start))
# concurrent
def concurrent_f(x):
global result
result = f(result)
result = 3
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as exector:
futures = [exector.submit(concurrent_f, i) for i in range(20)]
_ = concurrent.futures.as_completed(futures)
print('Result is very large. Only printing the last 5 digits:', result % 100000)
print('Concurrent took: %.2f seconds.' % (timer() - start))