Python簡單多進程multiprocessing.Pool類

來源:互聯網
上載者:User

標籤:proc   pool   view   one   target   library   科學家   ESS   進度條   

轉自:偽·電腦科學家|真·碼農

首先介紹一個簡單粗暴,非常實用的工具,就是 multiprocessing.Pool。如果你的任務能用 ys = map(f, xs) 來解決,大家可能都知道,這樣的形式天生就是最容易並行的,那麼在 Python 裡面並行計算這個任務真是再簡單不過了。舉個例子,把每個數都平方:

 1 import multiprocessing 2  3 def f(x): 4     return x * x 5  6 cores = multiprocessing.cpu_count() 7 pool = multiprocessing.Pool(processes=cores) 8 xs = range(5) 9 10 # method 1: map11 print pool.map(f, xs)  # prints [0, 1, 4, 9, 16]12 13 # method 2: imap14 for y in pool.imap(f, xs):15     print y            # 0, 1, 4, 9, 16, respectively16 17 # method 3: imap_unordered18 for y in pool.imap_unordered(f, xs):19     print(y)           # may be in any order

map 直接返回列表,而 i 開頭的兩個函數返回的是迭代器;imap_unordered 返回的是無序的。

當計算時間比較長的時候,我們可能想要加上一個進度條,這個時候 i 系列的好處就體現出來了。另外,有一個小技巧,就是輸出 \r 可以使得游標回到行首而不換行,這樣就可以製作簡易的進度條了。

1 cnt = 02 for _ in pool.imap_unordered(f, xs):3     sys.stdout.write(‘done %d/%d\r‘ % (cnt, len(xs)))4     cnt += 1

 

Python簡單多進程multiprocessing.Pool類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.