Skip to content

Commit e4da62c

Browse files
committed
Threading\S01-04-cpu-bound-sync-vs-threading-vs-multiprocessing
1 parent d164dad commit e4da62c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from time import time
2+
3+
start = time()
4+
5+
def count_down(n):
6+
while n > 0:
7+
n -= 1
8+
9+
###############################################################
10+
# Sync : Execution time for example : 17.773974657058716 sec
11+
count_down(100000000)
12+
count_down(100000000)
13+
end = time()
14+
print(f"Sequential: {end-start}")
15+
16+
###############################################################
17+
# Threading : Execution time for example : 20.466705083847046 sec
18+
from threading import Thread
19+
20+
thread1 = Thread(target=count_down, args=(100000000,))
21+
thread2 = Thread(target=count_down, args=(100000000,))
22+
thread1.start()
23+
thread2.start()
24+
thread1.join()
25+
thread2.join()
26+
27+
end = time()
28+
print(f"Threading: {end-start}")
29+
30+
###############################################################
31+
# Multiprocessing : Execution time for example : 12.150790929794312 sec
32+
from multiprocessing import Process
33+
34+
if __name__ == "__main__":
35+
p1 = Process(target=count_down, args=(100000000, ))
36+
p2 = Process(target=count_down, args=(100000000, ))
37+
p1.start()
38+
p2.start()
39+
p1.join()
40+
p2.join()
41+
42+
end = time()
43+
print(f"Multiprocessing: {end-start}")
44+
45+

0 commit comments

Comments
 (0)