如何使用Python并行化这个令人尴尬的并行循环

时间:2016-07-04 15:20:10

标签: python parallel-processing joblib

我有一个令人尴尬的并行循环:

# Definitions

def exhaustiveExplorationsWithSimilarityAll(inputFolder, outputFolder, similarityMeasure):
    phasesSpeedupDictFolder=parsePhasesSpeedupDictFolder(inputFolder)
    avgSpeedupProgramDict=computeAvgSpeedupProgram(phasesSpeedupDictFolder)
    parameters={
        PROGRAMSPHASESSPEEDUPDICTS:phasesSpeedupDictFolder,
        PROGRAMSAVGSPEEDUPDICT:avgSpeedupProgramDict
    }
similarityHandler= SimilarityHandler(similarityMeasure,parameters)



# Sequential running

for fileName in os.listdir(inputFolder):
    print fileName
    exhaustiveExplorationsWithSimilarity(inputFolder + fileName, outputFolder + fileName, similarityHandler)

我希望使用Joblib并行:

使其并行
# Parallel version

num_cores = multiprocessing.cpu_count()

parallel= Parallel(n_jobs=num_cores)
    for fileName in os.listdir(inputFolder):
        print fileName
        parallel(delayed(exhaustiveExplorationsWithSimilarity(inputFolder + fileName, outputFolder + fileName, similarityHandler)))

其他版本:

arg_generator = ((inputFolder + fileName, outputFolder + fileName, similarityHandler) for fileName in os.listdir(inputFolder))
parallel(delayed(exhaustiveExplorationsWithSimilarity)(arg_generator))

但在运行时投诉:

parallel(delayed(exhaustiveExplorationsWithSimilarity(inputFolder + fileName, outputFolder + fileName, similarityHandler)))
  File "/usr/lib/pymodules/python2.7/joblib/parallel.py", line 516, in __call__
    for function, args, kwargs in iterable:
TypeError: 'function' object is not iterable

我在这里缺少什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您仍然在循环中调用exhaustiveExplorationsWithSimilarity(连续),但是您将结果传递给delayed

在文档https://pythonhosted.org/joblib/parallel.html#common-usage中,您似乎需要执行以下操作:

parallel = Parallel(n_jobs=num_cores)
parallel(delayed(exhaustiveExplorationsWithSimilarity)(inputFolder + fileName, outputFolder + fileName, similarityHandler) for fileName in os.listdir(inputFolder))