我在Ubuntu上用python编写MinCut-graph问题的代码,在证明了单线程实现的正确性之后,我试图使用多线程/多处理来加快速度,但是我的代码速度减慢了。
我注意到了一个奇怪的行为,当我使用2个线程时,算法函数执行所花费的时间比单线程实现的时间翻了一倍,抵消了拥有2个线程的收益,并且由于多处理开销而导致了速度的降低,我不知道真正的原因,我唯一可能的解释是单核处理器,但事实并非如此,因为我的笔记本电脑有Intel®core™ i5-6200U CPU@2.30GHz×4
数字
单线程:迭代时间(主要是随机收缩函数的运行时间)平均为200mstime allocation, rand sel time 0.00 collapse time 0.12 self loops time 0.08
iteration # 6882 of 211931 took time 0.20 Graph creation time 0.00 alg run time 0.20 elasped time 1439.17 total time 42797.71 progress 3.36 cut = 9
使用2个线程from multithreading import Thread:2个并行迭代时间平均为470毫秒,因为函数速度从200毫秒降低到大约470毫秒,因为我正在等待加入,所以将采取最坏的情况
^{pr2}$
使用2个进程from multiprocessing import Process:2次并行迭代的平均时间是460ms,因为函数速度从200毫秒降低到了460毫秒,因为我正在等待加入,所以会出现最坏的情况。在time allocation, rand sel time 0.00 collapse time 0.24 self loops time 0.16
time allocation, rand sel time 0.00 collapse time 0.24 self loops time 0.16
iteration # 48 of 211931 took time 0.46 Graph creation time 0.05 alg run time 0.41 elasped time 10.96 total time 48907.02 progress 0.02 cut = None
我的预期是2次迭代将花费200毫秒或略多一倍的速度,我的代码,但似乎现在随机收缩函数运行时间翻倍,因此否定了并行性的影响
编码
我删除了计算和记录时间的行,以减少混乱def randomContraction(G, cut, i):
while G.numNodes() > 2 :
edgeIndex = G.randEdgeIndex()
G.collapse(edgeIndex)
G.removeSelfLoops()
cut[i] = G.cut()
return
def kragerMinCut(list):
num_threads = 2
elapsed = 0
n = len(list)
orig = Graph(list)
iterations = int(n*n*math.log(n))
threads = [None] * num_threads
G = [None] * num_threads
cut = [None] * iterations
i = 0
while i < iterations:
for j in range(len(G)):
G[j] = copy.deepcopy(orig)
for j in range(len(threads)):
threads[j] = Process(target=randomContraction, args=(G[j], cut, j+i))
threads[j].start()
for j in range(len(threads)):
threads[j].join()
i += num_threads
print(cut)
return min(cut)