![](/img/trans.png)
[英]Python - Why would multiprocessing code be slower than single threaded?
[英]Why python multiprocessing in this code is slower?
我有此示例代碼。 我正在做一些數學計算(圖形理論),並且想提高速度,所以我決定采用多處理,但是令人驚訝的是,同一代碼的運行速度甚至比單進程版本還要慢。
我希望如果您有一個列表,並且將其分成兩半並啟動兩個過程,則大約需要花費一半的時間。 我不認為我有一些同步問題,所以為什么這么慢?
from multiprocessing import Process, Queue
def do_work(queue, aList):
for elem in aList:
newList.append(a_math_function(elem))
queue.put(max(newList))
return max(newList)
def foo():
#I have let's say aList with 100000 objects
q1 = Queue(); q2 = Queue()
p1 = Process(target=do_work, args=[q1, aList[0: size/2])])
p2 = Process(target=do_work, args=[q2, aList[size/2+1: size])])
p1.start(); p2.start()
p1.join(); p2.join()
print(max(q1.get(),q2.get())
不要嘗試使用多處理,而要減少正在執行的分配量。 您只是用臨時列表填充RAM(例如,通過流程的aList的一半,然后在每個流程中創建的newList列表)。 這很可能是造成速度緩慢的原因,因為大量的分配意味着大量的垃圾回收。
嘗試以此替換所有代碼並測量速度。
def foo():
print max(a_math_function(x) for x in aList)
使用multiprocessing.Pool.map()在工作人員之間分配工作負載並從中獲取結果匯總。
請參見下面的示例http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.AsyncResult.successful
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.