-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4_thread_process.py
72 lines (52 loc) · 1.68 KB
/
4_thread_process.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# CPU-bound process (computationally expensive task)
'''
Open pc CPU monitor:
- threading: threads running in different CPU but one at a time (all CPU usage is low % and shifting)
- processing: threads running in all CPUs at the same time (all CPUs usage 100%)
'''
import os
import time
from multiprocessing import Process
from threading import Thread
x=10000000
class CalculateSquareThread(Thread):
def run(self):
s=0
for n in range(x):
s+=n*n
return s
class CalculateSquareProcess(Process):
def run(self):
s=0
for n in range(x):
s+=n*n
return s
if __name__ == "__main__":
# create n threads for each CPU core
threads = [CalculateSquareThread() for cpu in range(os.cpu_count())]
start = time.time()
for t in threads:
t.start()
print(f'{t.name} started')
for t in threads:
t.join()
print(f'{t.name} ended')
end = time.time()
print(f'Threads work took {end - start} seconds')
# create n processes for each CPU core
processes = [CalculateSquareProcess() for cpu in range(os.cpu_count())]
start = time.time()
for p in processes:
p.start()
print(f'{p.name} started')
for p in processes:
p.join()
print(f'{p.name} ended')
end = time.time()
print(f'Processes work took {end - start} seconds')
'''
GIL prevents any two threads from using CPU for their work at the exact same time:
it means that threads are useless in Python for parallel processing as they all go in one process
- threading: 8 threads, 1 process, 1 CPU (8 shared)
- processing: 8 threads, 8 processes, 8 CPUs
'''