教你用一行Python代碼實(shí)現(xiàn)并行任務(wù)(附代碼)
Python在程序并行化方面多少有些聲名狼藉。撇開技術(shù)上的問題,例如線程的實(shí)現(xiàn)和GIL,我覺得錯(cuò)誤的教學(xué)指導(dǎo)才是主要問題。常見的經(jīng)典Python多線程、多進(jìn)程教程多顯得偏"重"。而且往往隔靴搔癢,沒有深入探討日常工作中最有用的內(nèi)容。
傳統(tǒng)的例子
簡單搜索下"Python多線程教程",不難發(fā)現(xiàn)幾乎所有的教程都給出涉及類和隊(duì)列的例子:
#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 不是嗎?
我并不是說使用生產(chǎn)者/消費(fèi)者模型處理多線程/多進(jìn)程任務(wù)是錯(cuò)誤的(事實(shí)上,這一模型自有其用武之地)。只是,處理日常腳本任務(wù)時(shí)我們可以使用更有效率的模型。
問題在于…
首先,你需要一個(gè)樣板類;
其次,你需要一個(gè)隊(duì)列來傳遞對(duì)象;
而且,你還需要在通道兩端都構(gòu)建相應(yīng)的方法來協(xié)助其工作(如果需想要進(jìn)行雙向通信或是保存結(jié)果還需要再引入一個(gè)隊(duì)列)。
worker越多,問題越多
按照這一思路,你現(xiàn)在需要一個(gè)worker線程的線程池。下面是一篇IBM經(jīng)典教程中的例子——在進(jìn)行網(wǎng)頁檢索時(shí)通過多線程進(jìn)行加速。
#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 workers
if __name__ == '__main__':
Producer()
這段代碼能正確的運(yùn)行,但仔細(xì)看看我們需要做些什么:構(gòu)造不同的方法、追蹤一系列的線程,還有為了解決惱人的死鎖問題,我們需要進(jìn)行一系列的join操作。這還只是開始……
至此我們回顧了經(jīng)典的多線程教程,多少有些空洞不是嗎?樣板化而且易出錯(cuò),這樣事倍功半的風(fēng)格顯然不那么適合日常使用,好在我們還有更好的方法。
何不試試 map
map這一小巧精致的函數(shù)是簡捷實(shí)現(xiàn)Python程序并行化的關(guān)鍵。map源于Lisp這類函數(shù)式編程語言。它可以通過一個(gè)序列實(shí)現(xiàn)兩個(gè)函數(shù)之間的映射。
urls = ['http://www.yahoo.com', 'http://www.reddit.com'] results = map(urllib2.urlopen, urls)
上面的這兩行代碼將 urls 這一序列中的每個(gè)元素作為參數(shù)傳遞到 urlopen 方法中,并將所有結(jié)果保存到 results 這一列表中。其結(jié)果大致相當(dāng)于:
results = [] for url in urls: results.append(urllib2.urlopen(url))
map 函數(shù)一手包辦了序列操作、參數(shù)傳遞和結(jié)果保存等一系列的操作。
為什么這很重要呢?這是因?yàn)榻柚_的庫,map可以輕松實(shí)現(xiàn)并行化操作。
在Python中有個(gè)兩個(gè)庫包含了map函數(shù): multiprocessing和它鮮為人知的子庫 multiprocessing.dummy.
這里多扯兩句:multiprocessing.dummy? mltiprocessing庫的線程版克???這是蝦米?即便在multiprocessing庫的官方文檔里關(guān)于這一子庫也只有一句相關(guān)描述。而這句描述譯成人話基本就是說:"嘛,有這么個(gè)東西,你知道就成."相信我,這個(gè)庫被嚴(yán)重低估了!
dummy是multiprocessing模塊的完整克隆,唯一的不同在于multiprocessing作用于進(jìn)程,而dummy模塊作用于線程(因此也包括了Python所有常見的多線程限制)。
所以替換使用這兩個(gè)庫異常容易。你可以針對(duì)IO密集型任務(wù)和CPU密集型任務(wù)來選擇不同的庫。
動(dòng)手嘗試
使用下面的兩行代碼來引用包含并行化map函數(shù)的庫:
from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool
實(shí)例化 Pool 對(duì)象:
pool = ThreadPool()
這條簡單的語句替代了example2.py中buildworkerpool函數(shù)7行代碼的工作。它生成了一系列的worker線程并完成初始化工作、將它們儲(chǔ)存在變量中以方便訪問。
Pool對(duì)象有一些參數(shù),這里我所需要關(guān)注的只是它的第一個(gè)參數(shù):processes. 這一參數(shù)用于設(shè)定線程池中的線程數(shù)。其默認(rèn)值為當(dāng)前機(jī)器CPU的核數(shù)。
一般來說,執(zhí)行CPU密集型任務(wù)時(shí),調(diào)用越多的核速度就越快。但是當(dāng)處理網(wǎng)絡(luò)密集型任務(wù)時(shí),事情有有些難以預(yù)計(jì)了,通過實(shí)驗(yàn)來確定線程池的大小才是明智的。
pool = ThreadPool(4) # Sets the pool size to 4
線程數(shù)過多時(shí),切換線程所消耗的時(shí)間甚至?xí)^實(shí)際工作時(shí)間。對(duì)于不同的工作,通過嘗試來找到線程池大小的最優(yōu)值是個(gè)不錯(cuò)的主意。
創(chuàng)建好Pool對(duì)象后,并行化的程序便呼之欲出了。我們來看看改寫后的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 workers pool = ThreadPool(4) # Open the urls in their own threads # and return the results results = pool.map(urllib2.urlopen, urls) #close the pool and wait for the work to finish pool.close() pool.join()
實(shí)際起作用的代碼只有4行,其中只有一行是關(guān)鍵的。map函數(shù)輕而易舉的取代了前文中超過40行的例子。為了更有趣一些,我統(tǒng)計(jì)了不同方法、不同線程池大小的耗時(shí)情況。
# 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)
結(jié)果:
# Single thread: 14.4 Seconds
# 4 Pool: 3.1 Seconds
# 8 Pool: 1.4 Seconds
# 13 Pool: 1.3 Seconds
很棒的結(jié)果不是嗎?這一結(jié)果也說明了為什么要通過實(shí)驗(yàn)來確定線程池的大小。在我的機(jī)器上當(dāng)線程池大小大于9帶來的收益就十分有限了。
另一個(gè)真實(shí)的例子
生成上千張圖片的縮略圖
這是一個(gè)CPU密集型的任務(wù),并且十分適合進(jìn)行并行化。
基礎(chǔ)單進(jìn)程版本
import os
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (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)
上邊這段代碼的主要工作就是將遍歷傳入的文件夾中的圖片文件,一一生成縮略圖,并將這些縮略圖保存到特定文件夾中。
這我的機(jī)器上,用這一程序處理6000張圖片需要花費(fèi)27.9秒。
如果我們使用map函數(shù)來代替for循環(huán):
import os
import PIL
from multiprocessing import Pool
from PIL import Image
SIZE = (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 秒!
雖然只改動(dòng)了幾行代碼,我們卻明顯提高了程序的執(zhí)行速度。在生產(chǎn)環(huán)境中,我們可以為CPU密集型任務(wù)和IO密集型任務(wù)分別選擇多進(jìn)程和多線程庫來進(jìn)一步提高執(zhí)行速度——這也是解決死鎖問題的良方。此外,由于map函數(shù)并不支持手動(dòng)線程管理,反而使得相關(guān)的debug工作也變得異常簡單。
到這里,我們就實(shí)現(xiàn)了(基本)通過一行Python實(shí)現(xiàn)并行化。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python 多核并行計(jì)算的示例代碼
- 用map函數(shù)來完成Python并行任務(wù)的簡單示例
- python開啟多個(gè)子進(jìn)程并行運(yùn)行的方法
- Python中使用多進(jìn)程來實(shí)現(xiàn)并行處理的方法小結(jié)
- Python實(shí)現(xiàn)數(shù)據(jù)庫并行讀取和寫入實(shí)例
- Python中運(yùn)行并行任務(wù)技巧
- python實(shí)現(xiàn)守護(hù)進(jìn)程、守護(hù)線程、守護(hù)非守護(hù)并行
- Python科學(xué)計(jì)算之Pandas詳解
- Python基于pyCUDA實(shí)現(xiàn)GPU加速并行計(jì)算功能入門教程
相關(guān)文章
Python如何實(shí)現(xiàn)播放本地音樂并在web頁面播放
這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)播放本地音樂并在web頁面播放,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02
OpenCV實(shí)現(xiàn)單目攝像頭對(duì)圖像目標(biāo)測距
這篇文章主要為大家詳細(xì)介紹了OpenCV實(shí)現(xiàn)單目攝像頭對(duì)圖像目標(biāo)測距,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
關(guān)于Python連接Cassandra容器進(jìn)行查詢的問題
這篇文章主要介紹了Python連接Cassandra容器進(jìn)行查詢的問題,問題的關(guān)鍵在于尋找到Cassandra的9042端口,從而獲取數(shù)據(jù),具有內(nèi)容詳情跟隨小編一起看看吧2021-11-11
python中DataFrame常用的描述性統(tǒng)計(jì)分析方法詳解
這篇文章主要介紹了python中DataFrame常用的描述性統(tǒng)計(jì)分析方法詳解,描述性統(tǒng)計(jì)分析是通過圖表或數(shù)學(xué)方法,對(duì)數(shù)據(jù)資料進(jìn)行整理、分析,并對(duì)數(shù)據(jù)的分布狀態(tài)、數(shù)字特征和隨機(jī)變量之間的關(guān)系進(jìn)行估計(jì)和描述的方法,需要的朋友可以參考下2023-07-07
Python實(shí)現(xiàn)自動(dòng)玩貪吃蛇程序
這篇文章主要介紹了通過Python實(shí)現(xiàn)的簡易的自動(dòng)玩貪吃蛇游戲的小程序,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)一學(xué)2022-01-01
詳解Python中如何寫控制臺(tái)進(jìn)度條的整理
這篇文章主要介紹了詳解Python中如何寫控制臺(tái)進(jìn)度條的整理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
python 實(shí)現(xiàn)批量圖片識(shí)別并翻譯
這篇文章主要介紹了python 實(shí)現(xiàn)批量圖片識(shí)別并翻譯,幫助大家利用python處理圖片,感興趣的朋友可以了解下2020-11-11

