Python 函数列表的并行执行

Python 函数列表的并行执行,python,parallel-processing,multiprocessing,python-multiprocessing,Python,Parallel Processing,Multiprocessing,Python Multiprocessing,因此,使用多进程模块可以轻松地使用以下不同参数并行运行函数: from multiprocessing import Pool def f(x): return x**2 p = Pool(2) print(p.map(f, [1, 2])) 但我对在同一个参数上执行函数列表感兴趣。假设我有以下两个函数: def f(x): return x**2 def g(x): return x**3 + 2 如何为同一个参数(例如x=1)并行执行它们?您可以使用Po

因此,使用多进程模块可以轻松地使用以下不同参数并行运行函数:

from multiprocessing import Pool

def f(x):
    return x**2


p = Pool(2)
print(p.map(f, [1, 2]))
但我对在同一个参数上执行函数列表感兴趣。假设我有以下两个函数:

def f(x):
    return x**2


def g(x):
    return x**3 + 2

如何为同一个参数(例如x=1)并行执行它们?

您可以使用
Pool。为此,请应用\u async()
。将任务以(函数、参数\u元组)的形式捆绑起来,并将每个任务馈送到
apply\u async()

示例输出:

[100, 1000]

Process finished with exit code 0
print(result)

[(0, 2), (1, 3), (4, 10), (9, 29), (16, 66), (25, 127), (36, 218), (49, 345), 
(64, 514), (81, 731), (100, 1002), (121, 1333), (144, 1730), (169, 2199), 
(196, 2746), (225, 3377), (256, 4098), (289, 4915), (324, 5834), (361, 6861), 
(400, 8002), (441, 9263), (484, 10650), (529, 12169), (576, 13826), (625, 
15627), (676, 17578), (729, 19685), (784, 21954), (841, 24391), (900, 27002), 
(961, 29793)]

print(t1.timeit(1))
    5.000001692678779e-07         #(with 16 cpus and 64 Gb RAM) 

您可以返回一个元组。使用轻量级模块:joblib,可以非常轻松、紧凑地完成这项工作。我推荐joblib,因为它是轻量级的

from joblib import Parallel, delayed
import multiprocessing
import timeit


# Implementation 1
def f(x):    
    return x**2, x**3 + 2


#Implementation 2 for a more sophisticated second or more functions
def g(x):
    return  x**3 + 2


def f(x):    
    return x**2, g(x)


if __name__ == "__main__":
  inputs = [i for i in range(32)]
  num_cores = multiprocessing.cpu_count()
  t1 = timeit.Timer()
  result = Parallel(n_jobs=num_cores)(delayed(f)(i) for i in inputs)
  print(t1.timeit(1)) 
使用您在问题中已经使用的multiprocessing.Pool

from multiprocessing import Pool, cpu_count
import timeit


def g(x):
    return x**3 + 2


def f(x):    
    return x**2, g(x)

if __name__ == "__main__":
  inputs = [i for i in range(32)]
  num_cores = cpu_count()
  p = Pool(num_cores)
  t1 = timeit.Timer()
  result = p.map(f, inputs)
  print(t1.timeit(1))
  print(result)    
示例输出:

[100, 1000]

Process finished with exit code 0
print(result)

[(0, 2), (1, 3), (4, 10), (9, 29), (16, 66), (25, 127), (36, 218), (49, 345), 
(64, 514), (81, 731), (100, 1002), (121, 1333), (144, 1730), (169, 2199), 
(196, 2746), (225, 3377), (256, 4098), (289, 4915), (324, 5834), (361, 6861), 
(400, 8002), (441, 9263), (484, 10650), (529, 12169), (576, 13826), (625, 
15627), (676, 17578), (729, 19685), (784, 21954), (841, 24391), (900, 27002), 
(961, 29793)]

print(t1.timeit(1))
    5.000001692678779e-07         #(with 16 cpus and 64 Gb RAM) 
对于:inputs=range(2000),时间为: 1.10000190490391E-06