教你用一行Python代码实现并行(转)
教你用一行Python代码实现并行
本文教你通过一行Python实现并行化。
Python在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和GIL,我觉得错误的教学指导才是主要问题。常见的经典Python多线程、多进程教程多显得偏"重"。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。
传统的例子
简单搜索下"Python多线程教程",不难发现几乎所有的教程都给出涉及类和队列的例子:
#Example.py'''Standard Producer/Consumer Threading Pattern'''import timeimport threadingimport Queueclass Consumer(threading.Thread):def __init__(self, queue):threading.Thread.__init__(self)self._queue = queuedef 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 loopbreak# "Processes" (or in our case, prints) the queue itemprint "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 workerworker = Consumer(queue)# start calls the internal run() method to# kick off the threadworker.start()# variable to keep track of when we startedstart_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 processqueue.put('something at %s' % time.time())# Sleep a bit just to avoid an absurd number of messagestime.sleep(1)# This the "poison pill" method of killing a thread.queue.put('quit')# wait for the thread to close downworker.join()if __name__ == '__main__':Producer()
哈,看起来有些像 Java 不是吗?
我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。
问题在于…
首先,你需要一个样板类;
其次,你需要一个队列来传递对象;
而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。
worker越多,问题越多
按照这一思路,你现在需要一个worker线程的线程池。下面是一篇IBM经典教程中的例子——在进行网页检索时通过多线程进行加速。
#Example2.py'''A more realistic thread pool example'''import timeimport threadingimport Queueimport urllib2class Consumer(threading.Thread):def __init__(self, queue):threading.Thread.__init__(self)self._queue = queuedef run(self):while True:content = self._queue.get()if isinstance(content, str) and content == 'quit':breakresponse = 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 processfor url in urls:queue.put(url)# Add the poison pillvfor 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 urllib2from multiprocessing.dummy import Pool as ThreadPoolurls = ['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 finishpool.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 osimport PILfrom multiprocessing import Poolfrom 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 osimport PILfrom multiprocessing import Poolfrom 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实现并行化。
教你用一行Python代码实现并行(转)的更多相关文章
- python基础===一行 Python 代码实现并行(转)
原文:https://medium.com/building-things-on-the-internet/40e9b2b36148 译文:https://segmentfault.com/a/119 ...
- 一行python代码实现树结构
树结构是一种抽象数据类型,在计算机科学领域有着非常广泛的应用.一颗树可以简单的表示为根, 左子树, 右子树. 而左子树和右子树又可以有自己的子树.这似乎是一种比较复杂的数据结构,那么真的能像我们在标题 ...
- 用一行Python代码制作动态二维码
在GitHub上发现了一个比较有意思的项目,只需要一行Python代码就可以快捷方便生成普通二维码.艺术二维码(黑白/彩色)和动态GIF二维码. GitHub网站参见:https://github.c ...
- 一行Python代码画心型
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/yanlaifan/article/deta ...
- 有趣的一行 Python 代码
https://mp.weixin.qq.com/s/o9rm4tKsJeEWyqQDgVEQiQ https://mp.weixin.qq.com/s/G5F_GaUGI0w-kugOZX145g ...
- 一行python代码搞定文件分享
给同事分享文件,如你所知通过聊天工具,网盘或linux命令各种方法,还有一个也可以尝试下:使用一行python代码快速搭建一个http服务器在局域网内进行下载. python3使用: python3 ...
- 忘带U盘了??别急!一行python代码即可搞定文件传输
近日发现了python一个很有趣的功能,今天在这里给大伙儿做一下分享 需求前提 1.想要拷贝电脑的文件到另一台电脑但是又没有U盘2.手机上想获取到存储在电脑的文件3.忘带U盘- 您也太丢三落四了吧,但 ...
- 一行 Python 代码能干嘛?
Python 有很多优雅有趣的代码写法,同时还很简短,以至于当我刚开始接触这个编程语言的时候,就爱不释手.而前几天的编程语言榜单中 Python 也超越了 Java 成为了第一,挺替 Python 开 ...
- Python和多线程(multi-threading)。这是个好主意码?列举一些让Python代码以并行方式运行的方法。
Python并不支持真正意义上的多线程.Python中提供了多线程包,但是如果你想通过多线程提高代码的速度,使用多线程包并不是个好主意.Python中有一个被称为Global Interpreter ...
随机推荐
- 【Python爬虫学习笔记(3)】Beautiful Soup库相关知识点总结
1. Beautiful Soup简介 Beautiful Soup是将数据从HTML和XML文件中解析出来的一个python库,它能够提供一种符合习惯的方法去遍历搜索和修改解析树,这将大大减 ...
- SQL Server, Cannot resolve the collation conflict
今天遇到一个较为头痛的问题: Cannot resolve the collation conflict between "Chinese_PRC_90_CI_AS" and &q ...
- 像黑客一样!Chrome 完全键盘操作指南(原生快捷键 + Vimium 插件)
有那么一波小伙伴,多数时候都不需要用到鼠标,通常他们正好是“黑客”.当你开始使用键盘操作一切时,便能体会到无需用鼠标瞄准按钮时的干脆,无需在键盘和鼠标之间移动手时的轻松. Chrome 原生自带大量快 ...
- qt creator在Qt5中中文显示的问题
当我们用Qt Creater时,经常出会出现如下问题: 处理方法如下:用记事本打开你的源代码,然后点另存为,utf-8,编码覆盖,这时中文就没问题了但是会乱码.在字符串前加个宏QStringLiter ...
- 51nod 1118 机器人走方格
M * N的方格,一个机器人从左上走到右下,只能向右或向下走.有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10^9 + 7的结果. 收起 输入 第1行,2个数M,N,中间用空格隔开 ...
- 接口测试框架——第一篇-大框架和setting.py常量文件
基础知识已经准备的差不多了,今天开始我们就开始写我们的接口测试框架,框架结构已经说过了: 今天我们先完善需要的常量,也就是setting.py文件中的内容,代码如下: # coding: utf-8 ...
- 接口结构+一个selenium例子
大家今天可以先建一个项目目录,明天我们在码代码: 我看好多朋友都在看selenium方面的东西,在这里给大家一个和讯网自动发文章的selenium代码,有兴趣的朋友可以试试,船长已亲测可用,不明白的地 ...
- verilog中的有符号数理解(转)
verilog中的有符号数运算 有符号数的计算:若有需要关于有号数的计算,应当利用Verilog 2001所提供的signed及$signed()机制. Ex: input signed [7:0] ...
- FastAdmin env.sample 的用法
FastAdmin env.sample 的用法 在 FastAdmin 的 1.0.0.20180513 中我提交了一个 PR,增加 env.sample 内容如下: [app] debug = f ...
- 【转】电信100M光纤无线下载速度仅为5MB/秒的困惑
原文网址:http://itbbs.pconline.com.cn/50463999.html 在江苏电信官方测速网站测速的.1.光猫F460有线连接至笔记本,下载速度为12MB/秒左右:2.F460 ...