在Python中是否有类似于C#优秀的Parallel.For?我只想做像
这样的计算[simu(c) for c in clusterSizes]
并行。存档的最简单方法是什么?
PS:我尝试过joblib,但在我的情况下,它只是启动,启动和启动进程,直到我必须重新启动我的机器。
答案 0 :(得分:7)
在python 3中,concurrent.futures(标准库中)有并行映射。我认为它甚至被反向移植为python 2.7的模块。 修改 http://pypi.python.org/pypi/futures
正如其他答案所述,线程对你没有帮助。相反,你必须使用多个过程。
从文档中编辑看起来就像这样简单:
with concurrent.futures.ProcessPoolExecutor() as executor:
for result in executor.map(simu, clusterSizes)
pass # save result
答案 1 :(得分:5)
joblib基于multiprocessing
,与@EwyynTomato在评论中指出的problem on Windows相同:脚本的主要入口点必须受到__name__ == "__main__"
检查的保护。< / p>
from joblib import Parallel, delayed
if __name__ == "__main__":
result = Parallel(n_jobs=-1)(delayed(simu)(c) for c in clusterSizes)
# process result
答案 2 :(得分:0)
在multiprocessing
包中,您可以创建Pool
对象,并使用map
方法:
请参阅http://docs.python.org/library/multiprocessing.html
与joblib一样,你必须使用__name__ == "__main__"
保护主入口点,否则你将创建一个fork炸弹(并且在导入脚本时需要重新启动计算机)。
您要映射的功能需要可以选择。
答案 3 :(得分:0)
我写了一个可能有帮助的小包:
from python-parallel-collections import parallel
#equal to [simu(c) for c in clusterSizes]
#performed in parallel using multiple processes
#the results are only evaluated on demand, such as with the call to list below
parallel_gen = parallel(clusterSizes)
lazy_results = parallel_gen.map(simu)
evaluated_results = list(lazy_results)
这是Python 2.7,需要
pip install futures
pip install python-parallel-collections
让我知道你的想法 https://github.com/gterzian/Python-Parallel-Collections
答案 4 :(得分:-3)
使用其他语言。由于GIL(全局解释器锁),Python中的非IO绑定并行性效率不高。