我有一个相当简单的嵌套for循环,迭代四个数组:
for a in a_grid:
for b in b_grid:
for c in c_grid:
for d in d_grid:
do_some_stuff(a,b,c,d) # perform calculations and write to file
也许这不是开始在4D网格上执行计算的最有效方式。我知道joblib
能够并行化两个嵌套的for循环,如this,但我很难将它推广到四个嵌套循环。有什么想法吗?
答案 0 :(得分:14)
我通常使用这种形式的代码:
#!/usr/bin/env python3
import itertools
import multiprocessing
#Generate values for each parameter
a = range(10)
b = range(10)
c = range(10)
d = range(10)
#Generate a list of tuples where each tuple is a combination of parameters.
#The list will contain all possible combinations of parameters.
paramlist = list(itertools.product(a,b,c,d))
#A function which will process a tuple of parameters
def func(params):
a = params[0]
b = params[1]
c = params[2]
d = params[3]
return a*b*c*d
#Generate processes equal to the number of cores
pool = multiprocessing.Pool()
#Distribute the parameter sets evenly across the cores
res = pool.map(func,paramlist)
答案 1 :(得分:1)
作业数与嵌套循环数无关。
在另一个答案中,碰巧是n_jobs=2
和2个循环,但这两个循环完全不相关。
这样想: 你有一堆函数调用;在你的情况下(展开循环):
do_some_stuff(0,0,0,0)
do_some_stuff(0,0,0,1)
do_some_stuff(0,0,0,2)
do_some_stuff(0,0,1,0)
do_some_stuff(0,0,1,1)
do_some_stuff(0,0,1,2)
...
并且您希望在一些作业中分发这些函数调用。
你可以使用2个工作,或10个或100个工作,这没关系。 Parallel
负责为您分发工作。
答案 2 :(得分:1)
如果您使用的工具可以轻松地并行化两个嵌套循环,而不是四个,您可以使用itertools.product
将四个嵌套for
循环减少为两个:
from itertools import product
for a, b in product(a_grid, b_grid):
for c, d in product(c_grid, d_grid):
do_some_stuff(a, b, c, d)