一行 Python 代码实现并行

译者:caspar
译文:'
'http://python.org/doc/'
'http://python.org/download/'
'http://python.org/getit/'
'http://python.org/community/'
'https://wiki.python.org/moin/'
'http://planet.python.org/'
'https://wiki.python.org/moin/localusergroups'
'http://python.org/psf/'
'http://docs.python.org/devguide/'
'http://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.urlopenurls)
#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)
# # ------- 13 pool ------- #
# pool = threadpool(13)
结果:
# singlethread: 14.4 seconds
# 4 pool: 3.1 seconds
# 8 pool: 1.4 seconds
# 13 pool: 1.3 seconds
很棒的结果不是吗?这一结果也说明了为什么要通过实验来确定线程池的大小。在我的机器上当线程池大小大于 9带来的收益就十分有限了。
另一个真实的例子
生成上千张图片的缩略图
这是一个 cpu密集型的任务,并且十分适合进行并行化。
基础单进程版本
importos
importpil
frommultiprocessingimportpool
frompilimportimage
size=(7575)
save_directory='thumbs'
defget_image_paths(folder):
return(os.path.join(folderf)
forfinos.listdir(folder)
if'jpeg'inf)
defcreate_thumbnail(filename):
im=image.open(filename)
im.thumbnail(sizeimage.antialias)
basefname=os.path.split(filename)
save_path=os.path.join(basesave_directoryfname)
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(foldersave_directory))
images=get_image_paths(folder)
forimageinimages:
create_thumbnail(image)
上边这段代码的主要工作就是将遍历传入的文件夹中的图片文件,一一生成缩略图,并将这些缩略图保存到特定文件夹中。
这我的机器上,用这一程序处理 6000张图片需要花费 27.9秒。
如果我们使用 map函数来代替 for循环:
importos
importpil
frommultiprocessingimportpool
frompilimportimage
size=(7575)
save_directory='thumbs'
defget_image_paths(folder):
return(os.path.join(folderf)
forfinos.listdir(folder)
if'jpeg'inf)
defcreate_thumbnail(filename):
im=image.open(filename)
im.thumbnail(sizeimage.antialias)
basefname=os.path.split(filename)
save_path=os.path.join(basesave_directoryfname)
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(foldersave_directory))
images=get_image_paths(folder)
pool=pool
pool.map(creat_thumbnailimages)
pool.close
pool.join
5.6秒!
虽然只改动了几行代码,我们却明显提高了程序的执行速度。在生产环境中,我们可以为 cpu密集型任务和 io密集型任务分别选择多进程和多线程库来进一步提高执行速度——这也是解决死锁问题的良方。此外,由于 map函数并不支持手动线程管理,反而使得相关的 debug工作也变得异常简单。
到这里,我们就实现了(基本)通过一行python实现并行化。
update:
译文已获作者 chris授权
题图:pexels,cc0授权。