[問題] python multiProcess效能很差?

看板Python作者 (里歐)時間10年前 (2015/04/28 11:02), 編輯推噓3(3015)
留言18則, 4人參與, 最新討論串1/4 (看更多)
主要是參考segmentfault的這篇 http://segmentfault.com/a/1190000000414339 看起來很有效,可是實際... if __name__ == "__name__": pool = Pool() content = pool.map(transferConcat, [(obj_grab, content)])[0] pool.close() pool.join() def concatMessage(obj_grab, content): for logCatcher in obj_grab: for key in logCatcher.dic_map: regex = re.compile(key) for j in range(len(content)): for m in re.finditer(regex, content[j]): content[j] += " " + logCatcher.index + " " + logCatcher.dic_map[key] return content def transferConcat(args): return concatMessage(*args) 以上是我的代碼(部分,只貼問題點),執行時間22秒 若單純執行method大概也是22秒...等於沒加速... 我試過調整pool的數量,沒什麼效果 請問要怎麼做才能真正體現mulitiProcess的效能呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.221.50.98 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1430190169.A.3B0.html

04/28 12:56, , 1F
你實際上丟給 Pool.map(func, listarg1, listarg2)
04/28 12:56, 1F

04/28 12:57, , 2F
listargx = [x1, x2, ...] Pool 會並行執行 x1 和 x2
04/28 12:57, 2F

04/28 12:57, , 3F
但你只給了一組 input 所以實際上就是沒加速
04/28 12:57, 3F

04/28 16:13, , 4F
等於 pool.map(concatMessage, [obj_grab], [content])
04/28 16:13, 4F

04/28 20:22, , 5F
所以一組就不行嗎? 那有其它方式可以加速for loop嗎?
04/28 20:22, 5F

04/28 20:28, , 6F
對平行化完全沒有概念的話, 還是不要用比較好
04/28 20:28, 6F

04/28 21:41, , 7F
pool.map(cM, [obj1, obj2, ...], [c1, c2, ...])
04/28 21:41, 7F

04/28 21:41, , 8F
這樣就會有平行的效果,multiprocess 的對象是很明確的
04/28 21:41, 8F

04/28 21:42, , 9F
可以加速 for loop,就要針對 for loop 裡面的邏輯設計
04/28 21:42, 9F

04/28 22:39, , 10F
Python Concurrency From the Ground Up - PyCon 2015
04/28 22:39, 10F

04/28 22:39, , 11F
看看 David Beazley 大師的影片 http://goo.gl/oCuZaJ
04/28 22:39, 11F

04/29 00:22, , 12F
基本上 Python 的 multiprocessing 是以 tasks 為單位
04/29 00:22, 12F

04/29 00:22, , 13F
你必須要自己先把工作轉化成一堆 task 再來進行平行
04/29 00:22, 13F

04/29 00:23, , 14F
畢竟這不像 OpenMP 加個 #pragma omp parallel 就會動
04/29 00:23, 14F

04/29 00:24, , 15F
就像 ccwang002 提到的,你的 task 目前只有一個...
04/29 00:24, 15F

04/29 00:26, , 16F
你可以嘗試著把第一層迴圈展開,換成用 map 的寫法就好
04/29 00:26, 16F

04/29 00:32, , 17F
處理的 func 裡面不要去存取共享變數,讓每個 process
04/29 00:32, 17F

04/29 00:33, , 18F
都能夠獨立的跑完它的結果,之後再把結果進行 reduce
04/29 00:33, 18F
文章代碼(AID): #1LFlXPEm (Python)
文章代碼(AID): #1LFlXPEm (Python)