在这里,您正在创建 1Process
每个任务。这将并行运行您的所有任务,但它会给您的计算机带来沉重的开销,因为您的调度程序需要管理许多进程。这可能会导致系统冻结,因为您的程序使用了太多资源。
这里的一个解决方案可能是使用multiprocessing.Pool
运行给定数量的进程同时执行某些任务:
import multiprocessing as mp
def do_big_calculation(args):
sub_list, b, c = args
return 1
if __name__ == '__main__':
b, c = 1, 1
ll = [([1, 2, 3, 4], b, c),
([5, 6, 7, 8], b, c),
([9, 10, 11, 12], b, c)]
pool = mp.Pool(4)
result = pool.map(do_big_calculation, ll)
pool.terminate()
print(result)
如果您准备使用第三方库,您还可以看看concurrent.futures https://github.com/agronholm/pythonfutures(你需要在python2.7中安装它,但它存在于python3.4+)或joblib http://pythonhosted.org/joblib/(可通过 pip 获得):
from joblib import Parallel, delayed
def do_big_calculation(sub_list, b, c):
return 1
if __name__ == '__main__':
b, c = 1, 1
ll = [([1, 2, 3, 4], b, c),
([5, 6, 7, 8], b, c),
([9, 10, 11, 12], b, c)]
result = Parallel(n_jobs=-1)(
delayed(do_big_calculation)(l, b, c) for l in ll)
print(result)
这种库的主要优点是它正在开发中,而multiprocessing
在python2.7中被冻结。因此,错误修复和改进相对频繁。
它还实现了一些巧妙的工具来减少计算开销。例如,它使用大 numpy 数组的内存映射(减少启动所有作业的内存占用)。