【问题标题】:Python multiprocessing slower than single threadPython多处理比单线程慢
【发布时间】:2016-11-08 02:49:58
【问题描述】:

我一直在玩多处理问题,并注意到我的算法在并行化时比在单线程时慢。

在我的代码中,我不共享内存。 而且我很确定我的算法(见代码),它只是嵌套循环,是 CPU 绑定的。

但是,无论我做什么。并行代码在我所有的计算机上运行速度慢 10-20%。

我还在 20 个 CPU 的虚拟机上运行此程序,并且每次单线程都优于多线程(实际上甚至比我的计算机还慢)。

from multiprocessing.dummy import Pool as ThreadPool
from multi import chunks
from random import random
import logging
import time
from multi import chunks

## Product two set of stuff we can iterate over
S = []
for x in range(100000):
  S.append({'value': x*random()})
H =[]
for x in range(255):
  H.append({'value': x*random()})

# the function for each thread
# just nested iteration
def doStuff(HH):
  R =[]
  for k in HH['S']:
    for h in HH['H']:
      R.append(k['value'] * h['value'])
  return R

# we will split the work
# between the worker thread and give it
# 5 item each to iterate over the big list
HChunks = chunks(H, 5)
XChunks = []

# turn them into dictionary, so i can pass in both
# S and H list
# Note: I do this because I'm not sure if I use the global
# S, will it spend too much time on cache synchronizatio or not
# the idea is that I dont want each thread to share anything.
for x in HChunks:
  XChunks.append({'H': x, 'S': S})

print("Process")
t0 = time.time()
pool = ThreadPool(4)
R = pool.map(doStuff, XChunks)
pool.close()
pool.join()

t1 = time.time()

# measured time for 4 threads is slower 
# than when i have this code just do 
# doStuff(..) in non-parallel way
# Why!?

total = t1-t0
print("Took", total, "secs")

打开了许多相关问题,但许多问题都针对代码结构不正确 - 每个工作人员都受 IO 限制等。

【问题讨论】:

标签: python multithreading


【解决方案1】:

您使用的是多线程,而不是多处理。虽然许多语言允许线程并行运行,但 python 不允许。线程只是一个单独的控制状态,即它拥有自己的堆栈、当前函数等。python 解释器只是不时在执行每个堆栈之间切换。

基本上,所有线程都在一个内核上运行。只有当您不受 CPU 限制时,它们才会加速您的程序。

multiprocessing.dummy 复制了多处理的 API,但不过是线程模块的包装器。

如果您受 CPU 限制,多线程通常比单线程。这是因为工作和处理资源保持不变,但是您增加了管理线程的开销,例如在它们之间切换。

如何解决这个问题:不要使用from multiprocessing.dummy import Pool as ThreadPool,而是使用multiprocessing.Pool as ThreadPool


您可能想阅读 GIL,即全局解释器锁。这就是阻止线程并行运行的原因(以及对单线程性能的影响)。 CPython 以外的 Python 解释器可能没有 GIL,并且能够在多个内核上运行多线程。

【讨论】:

  • 我的生活一直是个谎言。
  • @40Plot 不,Python 在它的方法上只是,嗯,奇怪而古老
猜你喜欢
  • 2023-03-31
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2020-08-15
相关资源
最近更新 更多