成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

一行代碼實現Python并行處理

開發(fā) 后端
Python 在程序并行化方面多少有些聲名狼藉。撇開技術上的問題,例如線程的實現和 GIL,我覺得錯誤的教學指導才是主要問題。

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

傳統(tǒng)的例子

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

  1. import os  
  2. import PIL  
  3. from multiprocessing import Pool  
  4. from PIL import Image  
  5. SIZE = (75,75)  
  6. SAVE_DIRECTORY = 'thumbs'  
  7. def get_image_paths(folder):  
  8.     return (os.path.join(folder, f)  
  9.             for f in os.listdir(folder)  
  10.             if 'jpeg' in f) 
  11. def create_thumbnail(filename):   
  12.     im = Image.open(filename)  
  13.     im.thumbnail(SIZE, Image.ANTIALIAS)  
  14.     base, fname = os.path.split(filename)  
  15.     save_path = os.path.join(base, SAVE_DIRECTORY, fname)  
  16.     im.save(save_path)  
  17. if __name__ == '__main__':  
  18.     folder = os.path.abspath(  
  19.         '11_18_2013_R000_IQM_Big_Sur_Mon__e10d1958e7b766c3e840')  
  20.     os.mkdir(os.path.join(folder, SAVE_DIRECTORY))  
  21.     images = get_image_paths(folder)  
  22.     pool = Pool()  
  23.     pool.map(creat_thumbnail, images)  
  24.     pool.close()  
  25.     pool.join() 

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

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

問題在于…

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

worker 越多,問題越多

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

  1. #Example2.py  
  2. '''  
  3. A more realistic thread pool example  
  4. ''' 
  5. import time  
  6. import threading  
  7. import Queue  
  8. import urllib2  
  9. class Consumer(threading.Thread):   
  10.     def __init__(self, queue):   
  11.         threading.Thread.__init__(self)  
  12.         self._queue = queue  
  13.     def run(self):  
  14.         while True:  
  15.             content = self._queue.get()  
  16.             if isinstance(content, str) and content == 'quit':  
  17.                 break 
  18.              response = urllib2.urlopen(content)  
  19.         print 'Bye byes!'  
  20. def Producer():  
  21.     urls = [  
  22.         'http://www.python.org', 'http://www.yahoo.com'  
  23.         'http://www.scala.org', 'http://www.google.com'  
  24.         # etc..  
  25.     ]  
  26.     queue = Queue.Queue()  
  27.     worker_threads = build_worker_pool(queue, 4)  
  28.     start_time = time.time()  
  29.     # Add the urls to process  
  30.     for url in urls:  
  31.         queue.put(url)    
  32.     # Add the poison pillv  
  33.     for worker in worker_threads:  
  34.         queue.put('quit')  
  35.     for worker in worker_threads:  
  36.         worker.join()  
  37.     print 'Done! Time taken: {}'.format(time.time() - start_time)  
  38. def build_worker_pool(queue, size):  
  39.     workers = []  
  40.     for _ in range(size):  
  41.         worker = Consumer(queue)  
  42.         worker.start()  
  43.         workers.append(worker)  
  44.     return workers  
  45. if __name__ == '__main__':  
  46.     Producer() 

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

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

何不試試 map

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

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

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

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

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

為什么這很重要呢?這是因為借助正確的庫,map 可以輕松實現并行化操作。

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

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

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

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

動手嘗試

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

  1. from multiprocessing import Pool  
  2. from multiprocessing.dummy import Pool as ThreadPool 

實例化 Pool 對象:

  1. pool = ThreadPool() 

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

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

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

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

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

創(chuàng)建好 Pool 對象后,并行化的程序便呼之欲出了。我們來看看改寫后的 example2.py 

  1. import urllib2  
  2. from multiprocessing.dummy import Pool as ThreadPool  
  3. urls = [  
  4.     'http://www.python.org',  
  5.     'http://www.python.org/about/', 
  6.     'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',  
  7.     'http://www.python.org/doc/',  
  8.     'http://www.python.org/download/',  
  9.     'http://www.python.org/getit/',  
  10.     'http://www.python.org/community/',  
  11.     'https://wiki.python.org/moin/',  
  12.     'http://planet.python.org/',  
  13.     'https://wiki.python.org/moin/LocalUserGroups',  
  14.     'http://www.python.org/psf/',  
  15.     'http://docs.python.org/devguide/',  
  16.     'http://www.python.org/community/awards/'  
  17.     # etc..  
  18.     ]  
  19. # Make the Pool of workers  
  20. pool = ThreadPool(4)  
  21. # Open the urls in their own threads  
  22. # and return the results  
  23. results = pool.map(urllib2.urlopen, urls)  
  24. #close the pool and wait for the work to finish  
  25. pool.close()  
  26. pool.join() 

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

  1. results = []  
  2. # for url in urls:  
  3. #   result = urllib2.urlopen(url)  
  4. #   results.append(result)  
  5. # # ------- VERSUS ------- #  
  6. # # ------- 4 Pool ------- #  
  7. pool = ThreadPool(4)  
  8. results = pool.map(urllib2.urlopen, urls)  
  9. # # ------- 8 Pool ------- #  
  10. pool = ThreadPool(8)  
  11. results = pool.map(urllib2.urlopen, urls)  
  12. # # ------- 13 Pool ------- #  
  13. pool = ThreadPool(13)  
  14. results = pool.map(urllib2.urlopen, urls) 

結果: 

  1. #        Single thread:  14.4 Seconds  
  2. #               4 Pool:   3.1 Seconds  
  3. #               8 Pool:   1.4 Seconds 
  4. #              13 Pool:   1.3 Seconds 

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

另一個真實的例子

生成上千張圖片的縮略圖

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

基礎單進程版本 

  1. import os  
  2. import PIL  
  3. from multiprocessing import Pool  
  4. from PIL import Image  
  5. SIZE = (75,75)  
  6. SAVE_DIRECTORY = 'thumbs'  
  7. def get_image_paths(folder):  
  8.     return (os.path.join(folder, f)  
  9.             for f in os.listdir(folder)  
  10.             if 'jpeg' in f)  
  11. def create_thumbnail(filename):   
  12.     im = Image.open(filename)  
  13.     im.thumbnail(SIZE, Image.ANTIALIAS)  
  14.     base, fname = os.path.split(filename)  
  15.     save_path = os.path.join(base, SAVE_DIRECTORY, fname)  
  16.     im.save(save_path)  
  17. if __name__ == '__main__':  
  18.     folder = os.path.abspath(  
  19.         '11_18_2013_R000_IQM_Big_Sur_Mon__e10d1958e7b766c3e840')  
  20.     os.mkdir(os.path.join(folder, SAVE_DIRECTORY))  
  21.     images = get_image_paths(folder)  
  22.     for image in images:  
  23.         create_thumbnail(Image) 

上邊這段代碼的主要工作就是將遍歷傳入的文件夾中的圖片文件,一一生成縮略圖,并將這些縮略圖保存到特定文件夾中。

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

如果我們使用 map 函數來代替 for 循環(huán): 

  1. import os  
  2. import PIL  
  3. from multiprocessing import Pool  
  4. from PIL import Image  
  5. SIZE = (75,75)  
  6. SAVE_DIRECTORY = 'thumbs'  
  7. def get_image_paths(folder):  
  8.     return (os.path.join(folder, f)  
  9.             for f in os.listdir(folder) 
  10.              if 'jpeg' in f)  
  11. def create_thumbnail(filename):   
  12.     im = Image.open(filename)  
  13.     im.thumbnail(SIZE, Image.ANTIALIAS)  
  14.     base, fname = os.path.split(filename) 
  15.      save_path = os.path.join(base, SAVE_DIRECTORY, fname)  
  16.     im.save(save_path)  
  17. if __name__ == '__main__':  
  18.     folder = os.path.abspath(  
  19.         '11_18_2013_R000_IQM_Big_Sur_Mon__e10d1958e7b766c3e840')  
  20.     os.mkdir(os.path.join(folder, SAVE_DIRECTORY))  
  21.     images = get_image_paths(folder)  
  22.     pool = Pool()  
  23.     pool.map(creat_thumbnail, images)  
  24.     pool.close()  
  25.     pool.join() 

5.6 秒!

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

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

 

責任編輯:龐桂玉 來源: 馬哥Linux運維
相關推薦

2022-04-09 09:11:33

Python

2017-04-13 19:20:18

Python代碼并行任務

2014-02-12 13:43:50

代碼并行任務

2016-12-02 08:53:18

Python一行代碼

2024-11-08 17:22:22

2021-11-02 16:25:41

Python代碼技巧

2020-08-12 14:54:00

Python代碼開發(fā)

2020-09-28 12:34:38

Python代碼開發(fā)

2024-11-20 07:00:00

代碼數據清洗Python

2017-04-05 11:10:23

Javascript代碼前端

2020-08-24 08:25:48

Python開發(fā)工具

2021-08-23 17:49:02

代碼開發(fā)模型

2024-05-31 13:14:05

2020-01-10 22:56:56

Python圖像處理Linux

2022-09-28 10:12:50

Python代碼可視化

2021-08-31 09:49:37

CPU執(zhí)行語言

2020-09-09 16:00:22

Linux進程

2023-09-12 10:10:57

開發(fā)者工具開源

2022-04-14 07:57:52

Python代碼熱力圖

2021-01-25 09:36:00

Python代碼文件
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产精品久久久久久久久免费桃花 | 羞羞视频网站在线观看 | 国产九九av | 一级欧美一级日韩片 | 国产激情91久久精品导航 | 羞羞的视频在线观看 | 国产精品自产拍在线观看蜜 | 亚洲国产精品一区 | 天堂久久一区 | 成人在线视频观看 | 337p日本欧洲亚洲大胆鲁鲁 | 欧美日韩精品久久久免费观看 | 日本精品免费在线观看 | 视频在线日韩 | 一区二区视频在线 | 久久蜜桃资源一区二区老牛 | 亚洲精品综合一区二区 | 免费av观看| 一区二区三区免费 | 久久9热 | 国产一区二区三区亚洲 | 久久久久久国产精品三区 | 伊人精品国产 | 久久国产精品72免费观看 | 日韩欧美在线视频 | 亚洲国产91 | 极情综合网 | 色综合视频在线 | 久久久精品一区 | 欧美一区二区三区在线播放 | 久久久久一区 | h视频在线免费观看 | 老牛嫩草一区二区三区av | 国产色婷婷精品综合在线播放 | 我爱操| 逼逼网 | 精品国产一区二区国模嫣然 | 黄色一级大片在线免费看产 | 日本久久福利 | 久久一区 | 天天视频一区二区三区 |