forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample3.py
More file actions
52 lines (38 loc) · 1.25 KB
/
example3.py
File metadata and controls
52 lines (38 loc) · 1.25 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# ch15/example3.py
import time
import threading
from multiprocessing import Pool
COUNT = 50000000
def countdown(n):
while n > 0:
n -= 1
if __name__ == '__main__':
#######################################################################
# Sequential
start = time.time()
countdown(COUNT)
print('Sequential program finished.')
print(f'Took {time.time() - start : .2f} seconds.')
print()
#######################################################################
# Multithreading
thread1 = threading.Thread(target=countdown, args=(COUNT // 2,))
thread2 = threading.Thread(target=countdown, args=(COUNT // 2,))
start = time.time()
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print('Multithreading program finished.')
print(f'Took {time.time() - start : .2f} seconds.')
print()
#######################################################################
# Multiprocessing
pool = Pool(processes=2)
start = time.time()
pool.apply_async(countdown, args=(COUNT//2,))
pool.apply_async(countdown, args=(COUNT//2,))
pool.close()
pool.join()
print('Multiprocessing program finished.')
print(f'Took {time.time() - start : .2f} seconds.')