首頁  >  文章  >  後端開發  >  一行 Python 程式碼實作並行

一行 Python 程式碼實作並行

WBOY
WBOY轉載
2023-04-12 19:04:29859瀏覽

一行 Python 程式碼實作並行

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

傳統的例子

#簡單搜尋下"Python 多執行緒教學",不難發現幾乎所有的教程都給涉及類別和佇列的範例

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()

#哈,看起來有些像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 workers

if __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 程式碼實作並行

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

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

dummy 是 multiprocessing 模組的完整克隆,唯一的不同在於 multiprocessing 作用於進程,而 dummy 模組作用於線程(因此也包括了 Python 所有常見的多線程限制)。 
所以替換使用這兩個函式庫異常容易。你可以針對 IO 密集型任務和 CPU 密集型任務來選擇不同的函式庫。

動手嘗試

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

from multiprocessing import Pool
from 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 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()

实际起作用的代码只有 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 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)

上边这段代码的主要工作就是将遍历传入的文件夹中的图片文件,一一生成缩略图,并将这些缩略图保存到特定文件夹中。

这我的机器上,用这一程序处理 6000 张图片需要花费 27.9 秒。

如果我们使用 map 函数来代替 for 循环:

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 秒!

虽然只改动了几行代码,我们却明显提高了程序的执行速度。在生产环境中,我们可以为 CPU 密集型任务和 IO 密集型任务分别选择多进程和多线程库来进一步提高执行速度——这也是解决死锁问题的良方。此外,由于 map 函数并不支持手动线程管理,反而使得相关的 debug 工作也变得异常简单。

到这里,我们就实现了(基本)通过一行 Python 实现并行化。

译者:caspar

译文:​https://www.php.cn/link/687fe34a901a03abed262a62e22f90db​​​​m/a/1190000000414339 

原文:https://medium.com/building-things-on-the-internet/40e9b2b36148

以上是一行 Python 程式碼實作並行的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除