-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sorting_with_mulprocessing.py
More file actions
61 lines (52 loc) · 1.57 KB
/
Copy pathmerge_sorting_with_mulprocessing.py
File metadata and controls
61 lines (52 loc) · 1.57 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
#!python3
import time
from numpy import random
#import concurrent.futures
import multiprocessing
def merge(larray, rarray):
i=j=0
sorted_array = []
while i < len(larray) and j < len(rarray):
if larray[i] <= rarray[j]:
sorted_array.append(larray[i])
i += 1
else:
sorted_array.append(rarray[j])
j +=1
if i == len(larray):
sorted_array.extend(rarray[j:])
else:
sorted_array.extend(larray[i:])
return sorted_array
def merge_sort(array):
if len(array) <= 1:
return array
if len(array) > 1:
larray, rarray = array[:len(array)//2], array[len(array)//2:]
larray = merge_sort(larray)
rarray = merge_sort(rarray)
return merge(larray, rarray)
def parallelit(array):
nofpros = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=nofpros)
chunk = len(array)//nofpros
data = [array[i*chunk:(i+1)*chunk] for i in range(nofpros)]
data = pool.map(merge_sort, data)
extra = data.pop() if len(data) % 2 == 1 else None
print(data)
for i in range(nofpros//2):
for j in range(0, len(data), 2):
data[i] = merge(data[j], data[j+1])
if extra:
data = merge(data, extra)
return data[0]
def main():
a = list(random.randint(1000, size=1_000_000))
#print(a)
start = time.time()
#a = parallelit(a)
print(parallelit(a))
finish = time.time()
print(f"\nit took {(finish-start):.2f} seconds to sort {len(a):,} items.")
if __name__ == "__main__":
main()