首先介绍一个简单粗暴,非常实用的工具,就是 multiprocessing.Pool。如果你的任务能用 ys = map(f, xs) 来解决,大家可能都知道,这样的形式天生就是最容易并行的,那么在 Python 里面并行计算这个任务真是再简单不过了。举个例子,把每个数都平方:
1 import multiprocessing
2
3 def f(x):
4 return x * x
5
6 cores = multiprocessing.cpu_count()
7 pool = multiprocessing.Pool(processes=cores)
8 xs = range(5)
9
10 # method 1: map
11 print pool.map(f, xs) # prints [0, 1, 4, 9, 16]
12
13 # method 2: imap
14 for y in pool.imap(f, xs):
15 print y # 0, 1, 4, 9, 16, respectively
16
17 # method 3: imap_unordered
18 for y in pool.imap_unordered(f, xs):
19 print(y) # may be in any order
map 直接返回列表,而 i 开头的两个函数返回的是迭代器;imap_unordered 返回的是无序的。
当计算时间比较长的时候,我们可能想要加上一个进度条,这个时候 i 系列的好处就体现出来了。另外,有一个小技巧,就是输出 \r 可以使得光标回到行首而不换行,这样就可以制作简易的进度条了。
1 cnt = 0
2 for _ in pool.imap_unordered(f, xs):
3 sys.stdout.write('done %d/%d\r' % (cnt, len(xs)))
4 cnt += 1