并行版本的排序算法更快/与串行版本相同吗?

时间:2019-08-21 16:31:18

标签: python-3.x multithreading multiprocessing

我正在尝试在排序算法上实现多线程和多处理。实现的方式是:

-初始化一万个物品的列表

-为每个元素分配一个介于0到100之间的随机变量

arr = [1] * 10000
for x, i in enumerate(arr):
    arr[x] = random.randint(0, 100)
t_arr = arr
m_arr = arr
s_arr = arr

-创建2个子列表-一个子列表的值小于或等于50,另一个子列表 然后,我对两个子列表并行使用冒泡排序。一种使用线程,一种使用进程。

理论上两者都应该更快,但是只有多重处理。多线程产生相同的结果

我已经尝试过其他排序算法,问题仍然存在。

# Threading Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in t_arr:
    if i <= 50:
        subarr1.append(i)
    else:
        subarr2.append(i)
# Sort first array
t1 = threading.Thread(target=bubbleSort, args=(subarr1,))
# Sort second array
t2 = threading.Thread(target=bubbleSort, args=(subarr2,))
t1.start()
t2.start()
t1.join()
t2.join()
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))


# Serial Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in s_arr:
    if i <= 50:
        subarr1.append(i)
    else:
        subarr2.append(i)
# Sort first array
bubbleSort(subarr1)
# Sort second array
bubbleSort(subarr2)
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))


# Multiprocessing Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in s_arr:
    if i <= 50:
        subarr1.append(i)
    else:
        subarr2.append(i)
# Sort first array
p1 = multiprocessing.Process(target=bubbleSort, args=(subarr1,))
# Sort second array
p2 = multiprocessing.Process(target=bubbleSort, args=(subarr2,))
p1.start()
p2.start()
p1.join()
p2.join()
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))
  • 多线程:大约6秒
  • 序列:大约6秒(类似于线程化)
  • 多重处理:大约3秒钟

这些结果是一致的。有什么建议吗?

0 个答案:

没有答案