-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent.py
More file actions
81 lines (60 loc) · 1.9 KB
/
Copy pathconcurrent.py
File metadata and controls
81 lines (60 loc) · 1.9 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import time
import threading
import asyncio
from multiprocessing import Process
def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
avg = sum_num / len(num)
time.sleep(1)
return avg
def main_sequential(list1, list2, list3):
s = time.perf_counter()
cal_average(list1)
cal_average(list2)
cal_average(list3)
elapsed = time.perf_counter() - s
print("Sequential Programming Elapsed Time: " + str(elapsed) + " seconds")
async def cal_average_async(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
avg = sum_num / len(num)
await asyncio.sleep(1)
return avg
async def main_async(list1, list2, list3):
s = time.perf_counter()
tasks = [cal_average_async(list1), cal_average_async(list2), cal_average_async(list3)]
await asyncio.gather(*tasks)
elapsed = time.perf_counter() - s
print("Asynchronous Programming Elapsed Time: " + str(elapsed) + " seconds")
def main_threading(list1, list2, list3):
s = time.perf_counter()
lists = [list1, list2, list3]
threads = []
for i in range(len(lists)):
x = threading.Thread(target=cal_average, args=(lists[i],))
for t in threads:
t.join()
elapsed = time.perf_counter() - s
print("Threading Elapsed Time: " + str(elapsed) + " seconds")
def main_multiprocessing(list1, list2, list3):
s = time.perf_counter()
lists = [list1, list2, list3]
processes = [Process(target=cal_average, args=(lists[x],)) for x in range(len(lists))]
for p in processes:
p.start()
for p in processes:
p.join()
elapsed = time.perf_counter() - s
print("Multiprocessing Elapsed Time: " + str(elapsed) + " seconds")
if __name__ == '__main__':
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = [2, 4, 6, 8, 10]
l3 = [1, 3, 5, 7, 9, 11]
main_sequential(l1, l2, l3)
loop = asyncio.get_event_loop()
loop.run_until_complete(main_async(l1, l2, l3))
main_threading(l1, l2, l3)
main_multiprocessing(l1, l2, l3)