来源:编程派

翻译:caspar

译文:https://segmentfault.com/a/1190000000414339

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

本文长度为5200字,建议阅读8分钟

本文教你通过一行Python实现并行化。

Python在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和GIL,我觉得错误的教学指导才是主要问题。常见的经典Python多线程、多进程教程多显得偏"重"。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。

传统的例子

简单搜索下"Python多线程教程",不难发现几乎所有的教程都给出涉及类和队列的例子:

  1. #Example.py

  2. '''

  3. Standard Producer/Consumer Threading Pattern

  4. '''

  5. import time

  6. import threading

  7. import Queue

  8. class Consumer(threading.Thread):

  9.    def __init__(self, queue):

  10.        threading.Thread.__init__(self)

  11.        self._queue = queue

  12.    def run(self):

  13.        while True:

  14.            # queue.get() blocks the current thread until

  15.            # an item is retrieved.

  16.            msg = self._queue.get()

  17.            # Checks if the current message is

  18.            # the "Poison Pill"

  19.            if isinstance(msg, str) and msg == 'quit':

  20.                # if so, exists the loop

  21.                break

  22.            # "Processes" (or in our case, prints) the queue item  

  23.            print "I'm a thread, and I received %s!!" % msg

  24.        # Always be friendly!

  25.        print 'Bye byes!'

  26. def Producer():

  27.    # Queue is used to share items between

  28.    # the threads.

  29.    queue = Queue.Queue()

  30.    # Create an instance of the worker

  31.    worker = Consumer(queue)

  32.    # start calls the internal run() method to

  33.    # kick off the thread

  34.    worker.start()

  35.    # variable to keep track of when we started

  36.    start_time = time.time()

  37.    # While under 5 seconds..

  38.    while time.time() - start_time < 5:

  39.        # "Produce" a piece of work and stick it in

  40.        # the queue for the Consumer to process

  41.        queue.put('something at %s' % time.time())

  42.        # Sleep a bit just to avoid an absurd number of messages

  43.        time.sleep(1)

  44.    # This the "poison pill" method of killing a thread.

  45.    queue.put('quit')

  46.    # wait for the thread to close down

  47.    worker.join()

  48. if __name__ == '__main__':

  49.    Producer()

哈,看起来有些像 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的核数。

一般来说,执行CPU密集型任务时,调用越多的核速度就越快。但是当处理网络密集型任务时,事情有有些难以预计了,通过实验来确定线程池的大小才是明智的。

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

线程数过多时,切换线程所消耗的时间甚至会超过实际工作时间。对于不同的工作,通过尝试来找到线程池大小的最优值是个不错的主意。

创建好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行的例子。为了更有趣一些,我统计了不同方法、不同线程池大小的耗时情况。

  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循环:

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

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

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

教你用一行Python代码实现并行(附代码)相关推荐

  1. python常用代码入门-入门十大Python机器学习算法(附代码)

    入门十大Python机器学习算法(附代码) 今天,给大家推荐最常用的10种机器学习算法,它们几乎可以用在所有的数据问题上: 1.线性回归 线性回归通常用于根据连续变量估计实际数值(房价.呼叫次数.总销 ...

  2. 混合整数规划MIP/线性规划LP+python(cplex库)实现 附代码

    文章目录 相关知识点 LP线性规划问题 MIP混合整数规划 MIP的Python实现(docplex库) MIP的Python实现(ortool库) 喜欢的话请关注我们的微信公众号~<你好世界炼 ...

  3. 混合整数规划MIP/线性规划LP+python(ortool库)实现 附代码

    文章目录 相关知识点 LP线性规划问题 MIP混合整数规划 MIP的Python实现(Ortool库) assert MIP的Python实现(docplex库) 喜欢的话请关注我们的微信公众号~&l ...

  4. Python科学绘图实例附代码

    Python绘图精简实例附代码 作者:金良(golden1314521@gmail.com) csdn博客:http://blog.csdn.net/u012176591 Python绘图精简实例附代 ...

  5. 每日小技巧——教你用一行Python代码去除照片背景

    哈喽~大家好,我是恰恰!欢迎来到周一的每日小技巧,今天来教大家如何使用Python去除照片背景,说到去除照片背景的方法,可能不会Python的小伙伴首先想到的是美图秀秀,或者使用photoshop,也 ...

  6. python代码在线回归中怎么运行_手把手教你用Python进行回归(附代码、学习资料)...

    原标题:手把手教你用Python进行回归(附代码.学习资料) 作者: GURCHETAN SINGH翻译:张逸校对:丁楠雅 本文共5800字,建议阅读8分钟. 本文从线性回归.多项式回归出发,带你用P ...

  7. 柱状图、堆叠柱状图、瀑布图有什么区别?怎样用Python绘制?(附代码)

    来源:大数据DT(ID:hzdashuju) 作者:屈希峰,资深Python工程师,知乎多个专栏作者 本文约8000字,建议阅读20分钟 柱状图是当前应用最广泛的图表之一,你几乎每天都可以在电子产品上 ...

  8. python循环语句-python语句中Python循环语句(附代码)

    python语句多如牛毛,对于很多初学者来说,不知道该如何下手.今天本文将着重讲述python语句中for语句和while语句.都知道这2种语句都属于循环语句,for语句属于遍历循环,while语句属 ...

  9. tensorRT-lenet C++代码分析【附代码】

    前面的文章中已经写了一个tensorRT简单的demo---lenet推理[tensorRT-lenet],实现了从torch模型转wts[同时也展示出了wts内网络的详细信息]再转engine后的推 ...

最新文章

  1. GPU与CPU交互技术
  2. 学习《Linux设备模型浅析之驱动篇》笔记(一)
  3. python的openpyxl模块下载_python解析.xls/.xlsx文件–openpyxl模块(第三方)
  4. 政府网站公祭日,如何使网站整体变灰
  5. 博客园出现了奇怪的cookie问题
  6. Docker 实战总结(非常全面)
  7. python 重命名的方法_Python下OS模块重命名方法renames
  8. python语法学习_python语法学习笔记
  9. requests模块报错:Use body.encode('utf-8') if you want to send it encoded in UTF-8.
  10. 测量程序运行时间的几个函数
  11. 一边撸猫一边写代码,Linus Torvalds 谈在家办公
  12. Sublime Text编写80×86汇编.asm文件的语法高亮插件
  13. Python中zip函数
  14. DBMS_SQL使用
  15. C#读写注册列表(写入注册列表,读取注册列表的数据)
  16. Linux下通过ODBC连接数据库及ODBC相关操作命令
  17. iOS 修改app名称
  18. vue移动端复杂表格表头,固定表头与固定第一列
  19. 缺省路由(默认路由)实验
  20. oracle常用分析函数与聚合函数的用法

热门文章

  1. android图片素材參考
  2. linux基础(8)-颜色显示
  3. StyleSheet文件中路径处理
  4. excel表格中IP地址排序
  5. 苹果cms10的php.ini目录列表,使用苹果CMSV10常见问题整理官方版
  6. mysql安装源是什么_mysql官方源安装的一些问题
  7. Python字符串编码坑彻底详细解决 何梁
  8. 知识图谱要看的书 了解的人 公众的号
  9. ATTENTION QKV理解
  10. ORACLE 查询约束