[英]Python multiprocessing doesn't use all cores on RHEL6
我一直在嘗試使用python多處理程序包來利用我的計算機的多個內核來加快我正在做的一些物理模擬。
我注意到,當我運行仿真時,最多使用了12個內核中的3個。 實際上,當我開始仿真時,它最初使用3個內核,然后過一會兒就使用1個內核。 有時從一開始就只使用一個或兩個內核。 我一直無法弄清楚為什么(除了關閉一些終端窗口(沒有任何活動進程)之外,我基本上什么都沒改變)。 (操作系統為Red Hat Enterprise Linux 6.0,Python版本為2.6.5。)
我通過改變將工作拆分成的塊的數量(2到120之間)(即創建的進程數量)進行了實驗,但這似乎沒有效果。
我在網上尋找有關此問題的信息,並通讀了該站點上的大多數相關問題(例如, 一個 , 兩個 ),但找不到解決方案。
(編輯:我只是嘗試在Windows 7下運行代碼,並且正在使用所有可用的內核。不過,我仍然想為RHEL修復此問題。)
這是我的代碼(省略了物理過程):
from multiprocessing import Queue, Process, current_process
def f(q,start,end): #a dummy function to be passed as target to Process
q.put(mc_sim(start,end))
def mc_sim(start,end): #this is where the 'physics' is
p=current_process()
print "starting", p.name, p.pid
sum_=0
for i in xrange(start,end):
sum_+=i
print "exiting", p.name, p.pid
return sum_
def main():
NP=0 #number of processes
total_steps=10**8
chunk=total_steps/10
start=0
queue=Queue()
subprocesses=[]
while start<total_steps:
p=Process(target=f,args=(queue,start,start+chunk))
NP+=1
print 'delegated %s:%s to subprocess %s' % (start, start+chunk, NP)
p.start()
start+=chunk
subprocesses.append(p)
total=0
for i in xrange(NP):
total+=queue.get()
print "total is", total
#two lines for consistency check:
# alt_total=mc_sim(0,total_steps)
# print "alternative total is", alt_total
while subprocesses:
subprocesses.pop().join()
if __name__=='__main__':
main()
(實際上,代碼基於此處的 Alex Martelli的答案。)
編輯2:最終問題在我不了解的情況下得以解決。 我沒有更改代碼,也沒有更改任何與操作系統相關的信息。 盡管如此,現在在運行代碼時,所有內核都已使用。 也許問題會在以后再次出現,但是目前我選擇不再進行進一步研究,因為它仍然有效。 感謝大家的幫助。
我在i7
處理器上使用Python版本2.7.3 x64
在Ubuntu 12.04 x64 (kernel 3.2.0-32-generic)
上運行了您的示例,系統報告的所有8個內核都完全過載(基於htop
觀察),所以您的問題是,先生,是基於OS的實現,並且代碼不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.