在函数有大量参数的情况下进行多处理

时间:2017-05-31 04:53:54

标签: python multiprocessing joblib

关于如何在多处理的进程池或joblib中实现/调用具有大范围参数的函数的任何想法,其中两个或三个参数随每次迭代而改变,其余的保持不变。

下面是循环(我需要并行运行):请注意这里只有idx,string和secondaryf更改。

sep = ['These limits may help reduce', 'though not completely eliminate', 'alcohol related risks']

for idx, string in enumerate(sep):

    print "working on", string
    base_dir = os.path.dirname(os.path.realpath(__file__))
    folder = os.path.join(base_dir, folder)
    secondaryf = os.path.join(folder, str(idx))
    print "making", secondaryf

    if not os.path.exists(secondaryf):
        os.makedirs(secondaryf)

    number_of_lines = countlines2(string)

    words_2(string, secondaryf, fontface, fontface_italic, 
            number_of_lines, highlight, 
            highlight_color, font_color, 
            key_color, first_key, second_key, 
            third_key, stroke_color, 
            stroke_width, txt_under_color)

我知道有一些关于将joblib用于多个参数但在我的情况下并非所有参数都会改变。以前我在我的一个项目中使用过类似的结构(只是一个例子)。

from joblib import Parallel, delayed

vertices = [100, 1000, 10000]
edge_probabilities = [.1, .2, .3, .4, .5, .6]
power_exponents = [2, 2.5, 3, 3.5, 4]
graph_types = ['Erdos_Renyi', 'Barabasi', 'Watts_Strogatz']

Parallel(n_jobs=6)(delayed(makeGraph)(graph_type=graph, nodes=vertex, edge_probability=prob, power_exponent=exponent) for vertex in vertices for prob in edge_probabilities for exponent in power_exponents for graph in graph_types)

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用functools.partial来修复不会更改的参数:假设您有一个函数f(a, b, c, d, e)并且您只想改变c和e。然后,您可以通过

获取函数f_partial(c, e)
f_partial = functools.partial(f, a=a_value, b=b_value, d=d_value)

然后,只需使用之前用于并行作业的模式。