用map函数来完成Python并行任务的简单示例
众所周知,Python的并行处理能力很不理想。我认为如果不考虑线程和GIL的标准参数(它们大多是合法的),其原因不是因为技术不到位,而是我们的使用方法不恰当。大多数关于Python线程和多进程的教材虽然都很出色,但是内容繁琐冗长。它们的确在开篇铺陈了许多有用信息,但往往都不会涉及真正能提高日常工作的部分。
经典例子
DDG上以“Python threading tutorial (Python线程教程)”为关键字的热门搜索结果表明:几乎每篇文章中给出的例子都是相同的类+队列。
事实上,它们就是以下这段使用producer/Consumer来处理线程/多进程的代码示例:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#Example.py'''Standard Producer/Consumer Threading Pattern''' import timeimport threadingimport 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。
我现在并不想说明使用Producer / Consume来解决线程/多进程的方法是错误的——因为它肯定正确,而且在很多情况下它是最佳方法。但我不认为这是平时写代码的最佳选择。
它的问题所在(个人观点)
首先,你需要创建一个样板式的铺垫类。然后,你再创建一个队列,通过其传递对象和监管队列的两端来完成任务。(如果你想实现数据的交换或存储,通常还涉及另一个队列的参与)。
Worker越多,问题越多。
接下来,你应该会创建一个worker类的pool来提高Python的速度。下面是IBM tutorial给出的较好的方法。这也是程序员们在利用多线程检索web页面时的常用方法。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#Example2.py'''A more realistic thread pool example''' import timeimport threadingimport Queueimport 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 = [ # 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语句。而这些还仅仅只是繁琐的开始!
我们目前为止都完成了什么?基本上什么都没有。上面的代码几乎一直都只是在进行传递。这是很基础的方法,很容易出错(该死,我刚才忘了在队列对象上还需要调用task_done()方法(但是我懒得修改了)),性价比很低。还好,我们还有更好的方法。
介绍:Map
Map是一个很棒的小功能,同时它也是Python并行代码快速运行的关键。给不熟悉的人讲解一下吧,map是从函数语言Lisp来的。map函数能够按序映射出另一个函数。例如
|
1
2
|
results = map(urllib2.urlopen, urls) |
这里调用urlopen方法来把调用结果全部按序返回并存储到一个列表里。就像:
|
1
2
3
|
results = []for url in urls: results.append(urllib2.urlopen(url)) |
Map按序处理这些迭代。调用这个函数,它就会返回给我们一个按序存储着结果的简易列表。
为什么它这么厉害呢?因为只要有了合适的库,map能使并行运行得十分流畅!

有两个能够支持通过map函数来完成并行的库:一个是multiprocessing,另一个是鲜为人知但功能强大的子文件:multiprocessing.dummy。
题外话:这个是什么?你从来没听说过dummy多进程库?我也是最近才知道的。它在多进程的说明文档里面仅仅只被提到了一句。而且那一句就是大概让你知道有这么个东西的存在。我敢说,这样几近抛售的做法造成的后果是不堪设想的!
Dummy就是多进程模块的克隆文件。唯一不同的是,多进程模块使用的是进程,而dummy则使用线程(当然,它有所有Python常见的限制)。也就是说,数据由一个传递给另一个。这能够使得数据轻松的在这两个之间进行前进和回跃,特别是对于探索性程序来说十分有用,因为你不用确定框架调用到底是IO 还是CPU模式。
准备开始
要做到通过map函数来完成并行,你应该先导入装有它们的模块:
|
1
2
|
from multiprocessing import Poolfrom multiprocessing.dummy import Pool as ThreadPool |
再初始化:
|
1
|
pool = ThreadPool() |
这简单的一句就能代替我们的build_worker_pool 函数在example2.py中的所有工作。换句话说,它创建了许多有效的worker,启动它们来为接下来的工作做准备,以及把它们存储在不同的位置,方便使用。
Pool对象需要一些参数,但最重要的是:进程。它决定pool中的worker数量。如果你不填的话,它就会默认为你电脑的内核数值。
如果你在CPU模式下使用多进程pool,通常内核数越大速度就越快(还有很多其它因素)。但是,当进行线程或者处理网络绑定之类的工作时,情况会比较复杂所以应该使用pool的准确大小。
|
1
|
pool = ThreadPool(4) # Sets the pool size to 4 |
如果你运行过多线程,多线程间的切换将会浪费许多时间,所以你最好耐心调试出最适合的任务数。
我们现在已经创建了pool对象,马上就能有简单的并行程序了,所以让我们重新写example2.py中的url opener吧!
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import urllib2from multiprocessing.dummy import Pool as ThreadPool urls = [ # 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行就完成了所有的工作。其中3句还是简单的固定写法。调用map就能完成我们前面例子中40行的内容!为了更形象地表明两种方法的差异,我还分别给它们运行的时间计时。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 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) |
结果:
|
1
2
3
4
|
# Single thread: 14.4 Seconds# 4 Pool: 3.1 Seconds# 8 Pool: 1.4 Seconds# 13 Pool: 1.3 Seconds |
相当出色!并且也表明了为什么要细心调试pool的大小。在这里,只要大于9,就能使其运行速度加快。
实例2:
生成成千上万的缩略图
我们在CPU模式下来完成吧!我工作中就经常需要处理大量的图像文件夹。其任务之一就是创建缩略图。这在并行任务中已经有很成熟的方法了。
基础的单线程创建
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import osimport PIL from multiprocessing import Poolfrom 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循环的话:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import osimport PIL from multiprocessing import Poolfrom 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(create_thumbnail,images) pool.close() pool.join() |
5.6秒!
对于只改变了几行代码而言,这是大大地提升了运行速度。这个方法还能更快,只要你将cpu 和 io的任务分别用它们的进程和线程来运行——但也常造成死锁。总之,综合考虑到 map这个实用的功能,以及人为线程管理的缺失,我觉得这是一个美观,可靠还容易debug的方法。
好了,文章结束了。一行完成并行任务。
用map函数来完成Python并行任务的简单示例的更多相关文章
- C#调用Python脚本的简单示例
C#调用Python脚本的简单示例 分类:Python (2311) (0) 举报 收藏 IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Huguni ...
- python信号signal简单示例
进程间通信之类的,用得着, 可以自定义接到信息之后的动作. file1.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os impor ...
- python selenium 最简单示例
使用 pip 安装 selenium 下载 chromedriver,添加在PATH中 # -*- coding: utf-8 -*- from selenium import webdriver ...
- Python基础总结之认识lambda函数、map函数、filter() 函数。第十二天开始(新手可相互督促)
今天周日,白天在学习,晚上更新一些笔记,希望对大家能更好的理解.学习python~ lambda函数,也就是大家说的匿名函数.它没有具体的名称,也可以叫做一句话函数,我觉得也不过分,大家看下代码,来体 ...
- 实现python中的map函数
假设Python没有提供map()函数,自行编写my_map()函数实现与map()相同的功能.以下代码在Python 2.7.8中实现. 实现代码: def my_map(fun,num): i = ...
- python map函数
map()函数 map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于li ...
- Python中的map()函数和reduce()函数的用法
Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下 Py ...
- python的map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于list [1, 2 ...
- Python中map()函数浅析
MapReduce的设计灵感来自于函数式编程,这里不打算提MapReduce,就拿python中的map()函数来学习一下. 文档中的介绍在这里: map(function, iterable, .. ...
随机推荐
- spring容器启动
1 主要类 ContextLoaderListener:注册在web.xml中,web应用启动时,会创建它,并回调它的initWebApplicationContext()方法,从而创建并启动spri ...
- Linux VPS上DenyHosts阻止SSH暴力攻击
2009年07月23日 下午 | 作者:VPS侦探 现在的互联网非常不安全,很多人没事就拿一些扫描机扫描ssh端口,然后试图连接ssh端口进行暴力破解(穷举扫描),所以建议vps主机的空间,尽量设置复 ...
- centos7下安装docker 17.x
docker的17.X版本与以前的docker安装有些不同,参考了下这篇文章http://www.itmuch.com/docker/docker-2/,以下是我的docker 17.X版本安装过程, ...
- 记录:Web无引用无配置方式动态调用WCF服务
这几年一直用WebApi较多,最近项目中有个需求比较适合使用WCF,以前也用过JQuery直接调用Wcf的,但是说实话真的忘了… 所以这次解决完还是花几分钟记录一下 WCF服务端:宿主在现有Win服务 ...
- C++代码规范之命名
C++代码规范之命名 一.命名的两个基本原则 1.含义清晰,不易混淆: 2.不和其它模块.系统API的命名空间相冲突. 二.命名通则 1.在所有命名中,都应使用标准的英文单词或缩写:不得使用拼音或拼音 ...
- Zookeeper--分布式锁和消息队列
在java并发包中提供了若干锁的实现,它们是用于单个java虚拟机进程中的:而分布式锁能够在一组进程之间提供互斥机制,保证在任何时刻只有一个进程可以持有锁. 分布式环境中多个进程的锁则可以使用Zook ...
- python 将html实体转回去
参考资料: http://www.360doc.com/content/17/0620/16/44530822_664927373.shtml https://blog.csdn.net/guzhou ...
- HDU-1937题解
一.题意 一个N*M的矩形,点表示空地,X表示非空地,给你一个数字k,让你在这N*M的区域内找出一个空地数量不小于k且面积最小的矩形.输出矩形的面积. PS:原题的题意是在难懂啊. 二.思路 1.朴素 ...
- 【UVA】1589 Xiangqi(挖坑待填)
题目 题目 分析 无力了,noip考完心力憔悴,想随便切道题却码了250line,而且还是错的,知道自己哪里错了,但特殊情况判起来太烦了,唯一选择是重构,我却没有这勇气. 有空再写吧,最近真的 ...
- Oracle回收站使用全攻略
摘要:回收站(Recycle Bin)从原理上来说就是一个数据字典表,放置用户删除(drop)掉的数据库对象信息.用户进行删除操作的对象并没有被数据库删除,仍然会占用空间.除非是由于用户手工进行Pur ...