-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithreading_vs_multiprocessing.py
More file actions
50 lines (44 loc) · 1.32 KB
/
Copy pathmultithreading_vs_multiprocessing.py
File metadata and controls
50 lines (44 loc) · 1.32 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
# ============================================
# Python Concurrency Playground
# Demonstrates:
# 1. Multiprocessing
# 2. Multithreading
#
# Goal: Simulate I/O-bound and CPU-bound tasks
# and see how concurrency improves performance.
# ============================================
import threading
import multiprocessing
import time
# A simple function that simulates a time-consuming task
def task(name):
print(f"{name} started")
time.sleep(2)
print(f"{name} finished")
# Multithreading example
def run_multithreading():
print("\n--- Multithreading Example ---")
threads = []
for i in range(3):
t = threading.Thread(target=task, args=(f"Thread-{i+1}",))
threads.append(t)
t.start()
for t in threads:
t.join()
# Multiprocessing example
def run_multiprocessing():
print("\n--- Multiprocessing Example ---")
processes = []
for i in range(3):
p = multiprocessing.Process(target=task, args=(f"Process-{i+1}",))
processes.append(p)
p.start()
for p in processes:
p.join()
if __name__ == "__main__":
start = time.time()
run_multithreading()
print(f"Multithreading took {time.time() - start:.2f} seconds")
start = time.time()
run_multiprocessing()
print(f"Multiprocessing took {time.time() - start:.2f} seconds")