教你用一行Python代碼實現並行任務(附代碼),一行python

來源:互聯網
上載者:User

教你用一行Python代碼實現並行任務(附代碼),一行python

Python在程式並行化方面多少有些聲名狼藉。撇開技術上的問題,例如線程的實現和GIL,我覺得錯誤的教學指導才是主要問題。常見的經典Python多線程、多進程教程多顯得偏"重"。而且往往隔靴搔癢,沒有深入探討日常工作中最有用的內容。

傳統的例子

簡單搜尋下"Python多線程教程",不難發現幾乎所有的教程都給出涉及類和隊列的例子:

#Example.py'''Standard Producer/Consumer Threading Pattern'''import time import threading import Queue class Consumer(threading.Thread):   def __init__(self, queue):     threading.Thread.__init__(self)    self._queue = queue   def run(self):    while True:       # queue.get() blocks the current thread until       # an item is retrieved.       msg = self._queue.get()       # Checks if the current message is       # the "Poison Pill"      if isinstance(msg, str) and msg == 'quit':        # if so, exists the loop        break      # "Processes" (or in our case, prints) the queue item        print "I'm a thread, and I received %s!!" % msg    # Always be friendly!     print 'Bye byes!'def Producer():  # Queue is used to share items between  # the threads.  queue = Queue.Queue()  # Create an instance of the worker  worker = Consumer(queue)  # start calls the internal run() method to   # kick off the thread  worker.start()   # variable to keep track of when we started  start_time = time.time()   # While under 5 seconds..   while time.time() - start_time < 5:     # "Produce" a piece of work and stick it in     # the queue for the Consumer to process    queue.put('something at %s' % time.time())    # Sleep a bit just to avoid an absurd number of messages    time.sleep(1)  # This the "poison pill" method of killing a thread.   queue.put('quit')  # wait for the thread to close down  worker.join()if __name__ == '__main__':  Producer()

哈,看起來有些像 Java 不是嗎?

我並不是說使用生產者/消費者模型處理多線程/多進程任務是錯誤的(事實上,這一模型自有其用武之地)。只是,處理日常指令碼任務時我們可以使用更有效率的模型。

問題在於…

首先,你需要一個樣板類;
其次,你需要一個隊列來傳遞對象;
而且,你還需要在通道兩端都構建相應的方法來協助其工作(如果需想要進行雙向通訊或是儲存結果還需要再引入一個隊列)。

worker越多,問題越多

按照這一思路,你現在需要一個worker線程的線程池。下面是一篇IBM經典教程中的例子——在進行網頁檢索時通過多線程進行加速。

#Example2.py'''A more realistic thread pool example '''import time import threading import Queue import urllib2 class Consumer(threading.Thread):   def __init__(self, queue):     threading.Thread.__init__(self)    self._queue = queue   def run(self):    while True:       content = self._queue.get()       if isinstance(content, str) and content == 'quit':        break      response = urllib2.urlopen(content)    print 'Bye byes!'def Producer():  urls = [    'http://www.python.org', 'http://www.yahoo.com'    'http://www.scala.org', 'http://www.google.com'    # etc..   ]  queue = Queue.Queue()  worker_threads = build_worker_pool(queue, 4)  start_time = time.time()  # Add the urls to process  for url in urls:     queue.put(url)   # Add the poison pillv  for worker in worker_threads:    queue.put('quit')  for worker in worker_threads:    worker.join()  print 'Done! Time taken: {}'.format(time.time() - start_time)def build_worker_pool(queue, size):  workers = []  for _ in range(size):    worker = Consumer(queue)    worker.start()     workers.append(worker)  return workersif __name__ == '__main__':  Producer()

這段代碼能正確的運行,但仔細看看我們需要做些什麼:構造不同的方法、追蹤一系列的線程,還有為瞭解決惱人的死結問題,我們需要進行一系列的join操作。這還只是開始……

至此我們回顧了經典的多線程教程,多少有些空洞不是嗎?樣板化而且易出錯,這樣事倍功半的風格顯然不那麼適合日常使用,好在我們還有更好的方法。

何不試試 map

map這一小巧精緻的函數是簡捷實現Python程式並行化的關鍵。map源於Lisp這類函數式程式設計語言。它可以通過一個序列實現兩個函數之間的映射。

urls = ['http://www.yahoo.com', 'http://www.reddit.com']results = map(urllib2.urlopen, urls)

上面的這兩行代碼將 urls 這一序列中的每個元素作為參數傳遞到 urlopen 方法中,並將所有結果儲存到 results 這一列表中。其結果大致相當於:

results = []for url in urls:   results.append(urllib2.urlopen(url))

map 函數一手包辦了序列操作、參數傳遞和結果儲存等一系列的操作。

為什麼這很重要呢?這是因為藉助正確的庫,map可以輕鬆實現並行化操作。

在Python中有個兩個庫包含了map函數: multiprocessing和它鮮為人知的子庫 multiprocessing.dummy.

這裡多扯兩句:multiprocessing.dummy? mltiprocessing庫的線程版複製?這是蝦米?即便在multiprocessing庫的官方文檔裡關於這一子庫也只有一句相關描述。而這句描述譯成人話基本就是說:"嘛,有這麼個東西,你知道就成."相信我,這個庫被嚴重低估了!

dummy是multiprocessing模組的完整複製,唯一的不同在於multiprocessing作用於進程,而dummy模組作用於線程(因此也包括了Python所有常見的多線程限制)。

所以替換使用這兩個庫異常容易。你可以針對IO密集型任務和CPU密集型任務來選擇不同的庫。

動手嘗試

使用下面的兩行代碼來引用包含並行化map函數的庫:

from multiprocessing import Poolfrom multiprocessing.dummy import Pool as ThreadPool

執行個體化 Pool 對象:

pool = ThreadPool()

這條簡單的語句替代了example2.py中buildworkerpool函數7行代碼的工作。它產生了一系列的worker線程並完成初始化工作、將它們儲存在變數中以方便訪問。

Pool對象有一些參數,這裡我所需要關注的只是它的第一個參數:processes. 這一參數用於設定線程池中的線程數。其預設值為當前機器CPU的核心數。

一般來說,執行CPU密集型任務時,調用越多的核速度就越快。但是當處理網路密集型任務時,事情有有些難以預計了,通過實驗來確定線程池的大小才是明智的。

pool = ThreadPool(4) # Sets the pool size to 4

線程數過多時,切換線程所消耗的時間甚至會超過實際工作時間。對於不同的工作,通過嘗試來找到線程池大小的最優值是個不錯的主意。

建立好Pool對象後,並行化的程式便呼之欲出了。我們來看看改寫後的example2.py

import urllib2 from multiprocessing.dummy import Pool as ThreadPool urls = [  'http://www.python.org',   'http://www.python.org/about/',  'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',  'http://www.python.org/doc/',  'http://www.python.org/download/',  'http://www.python.org/getit/',  'http://www.python.org/community/',  'https://wiki.python.org/moin/',  'http://planet.python.org/',  'https://wiki.python.org/moin/LocalUserGroups',  'http://www.python.org/psf/',  'http://docs.python.org/devguide/',  'http://www.python.org/community/awards/'  # etc..   ]# Make the Pool of workerspool = ThreadPool(4) # Open the urls in their own threads# and return the resultsresults = pool.map(urllib2.urlopen, urls)#close the pool and wait for the work to finish pool.close() pool.join() 

實際起作用的代碼只有4行,其中只有一行是關鍵的。map函數輕而易舉取代了前文中超過40行的例子。為了更有趣一些,我統計了不同方法、不同線程池大小的耗時情況。

# results = [] # for url in urls:#  result = urllib2.urlopen(url)#  results.append(result)# # ------- VERSUS ------- # # # ------- 4 Pool ------- # # pool = ThreadPool(4) # results = pool.map(urllib2.urlopen, urls)# # ------- 8 Pool ------- # # pool = ThreadPool(8) # results = pool.map(urllib2.urlopen, urls)# # ------- 13 Pool ------- # # pool = ThreadPool(13) # results = pool.map(urllib2.urlopen, urls)

結果:

#        Single thread:  14.4 Seconds
#               4 Pool:   3.1 Seconds
#               8 Pool:   1.4 Seconds
#              13 Pool:   1.3 Seconds

很棒的結果不是嗎?這一結果也說明了為什麼要通過實驗來確定線程池的大小。在我的機器上當線程池大小大於9帶來的收益就十分有限了。

另一個真實的例子

產生上千張圖片的縮圖

這是一個CPU密集型的任務,並且十分適合進行並行化。

基礎單進程版本

import os import PIL from multiprocessing import Pool from PIL import ImageSIZE = (75,75)SAVE_DIRECTORY = 'thumbs'def get_image_paths(folder):  return (os.path.join(folder, f)       for f in os.listdir(folder)       if 'jpeg' in f)def create_thumbnail(filename):   im = Image.open(filename)  im.thumbnail(SIZE, Image.ANTIALIAS)  base, fname = os.path.split(filename)   save_path = os.path.join(base, SAVE_DIRECTORY, fname)  im.save(save_path)if __name__ == '__main__':  folder = os.path.abspath(    '11_18_2013_R000_IQM_Big_Sur_Mon__e10d1958e7b766c3e840')  os.mkdir(os.path.join(folder, SAVE_DIRECTORY))  images = get_image_paths(folder)  for image in images:    create_thumbnail(Image)

上邊這段代碼的主要工作就是將遍曆傳入的檔案夾中的圖片檔案,一一產生縮圖,並將這些縮圖儲存到特定檔案夾中。

這我的機器上,用這一程式處理6000張圖片需要花費27.9秒。

如果我們使用map函數來代替for迴圈:

import os import PIL from multiprocessing import Pool from PIL import ImageSIZE = (75,75)SAVE_DIRECTORY = 'thumbs'def get_image_paths(folder):  return (os.path.join(folder, f)       for f in os.listdir(folder)       if 'jpeg' in f)def create_thumbnail(filename):   im = Image.open(filename)  im.thumbnail(SIZE, Image.ANTIALIAS)  base, fname = os.path.split(filename)   save_path = os.path.join(base, SAVE_DIRECTORY, fname)  im.save(save_path)if __name__ == '__main__':  folder = os.path.abspath(    '11_18_2013_R000_IQM_Big_Sur_Mon__e10d1958e7b766c3e840')  os.mkdir(os.path.join(folder, SAVE_DIRECTORY))  images = get_image_paths(folder)  pool = Pool()  pool.map(creat_thumbnail, images)  pool.close()  pool.join()

5.6 秒!

雖然只改動了幾行代碼,我們卻明顯提高了程式的執行速度。在生產環境中,我們可以為CPU密集型任務和IO密集型任務分別選擇多進程和多線程庫來進一步提高執行速度——這也是解決死結問題的良方。此外,由於map函數並不支援手動線程管理,反而使得相關的debug工作也變得異常簡單。

到這裡,我們就實現了(基本)通過一行Python實現並行化。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.