python执行速度太慢为什么还,为什么Python多处理减慢了函数的执行速度?

我在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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值