-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgil_example.py
More file actions
55 lines (42 loc) · 1.4 KB
/
gil_example.py
File metadata and controls
55 lines (42 loc) · 1.4 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
53
54
55
import threading
import time
def cpu_bound_task(iterations):
"""
A simple CPU-bound function.
It performs a large number of computations to keep the CPU busy.
"""
total = 0
for _ in range(iterations):
# Some repetitive math operation
for i in range(1000000):
total += i**2
return total
def run_single_thread(iterations):
start = time.time()
cpu_bound_task(iterations)
end = time.time()
print(f"Single-threaded: finished in {end - start:.2f} seconds.")
def run_multi_thread(iterations):
"""
Run two threads doing the same CPU-bound work.
Because of the GIL, only one thread can execute Python bytecode at a time.
We will see that this does not provide the same speedup you'd expect
if threads truly ran in parallel on multiple cores.
"""
start = time.time()
# Create two threads
t1 = threading.Thread(target=cpu_bound_task, args=(iterations,))
t2 = threading.Thread(target=cpu_bound_task, args=(iterations,))
# Start threads
t1.start()
t2.start()
# Wait for both threads to finish
t1.join()
t2.join()
end = time.time()
print(f"Multi-threaded: finished in {end - start:.2f} seconds.")
if __name__ == "__main__":
# Adjust the number of iterations as needed (higher = more CPU-bound work)
iterations = 50
run_single_thread(iterations)
run_multi_thread(iterations)