我有一个看起来像这样的Python程序:
total_error = []
for i in range(24):
error = some_function_call(parameters1, parameters2)
total_error += error
函数“ some_function_call”花费大量时间,我找不到降低该函数时间复杂度的简便方法。有没有一种方法可以减少执行并行任务时的执行时间,以后再将它们加到total_error中。我尝试使用pool和joblib,但均无法成功使用。
您还可以concurrent.futures
在Python 3中使用该接口,该接口比更为简单multiprocessing
。有关差异的更多详细信息,请参见此内容。
from concurrent import futures
total_error = 0
with futures.ProcessPoolExecutor() as pool:
for error in pool.map(some_function_call, parameters1, parameters2):
total_error += error
在这种情况下,parameters1
并且parameters2
应该是列表或可迭代的,其大小与您要运行该函数的次数相同(根据您的示例为24次)。
如果paramters<1,2>
不是可迭代/可映射的,但您只想运行该函数24次,则可以提交该函数的作业所需的次数,然后再使用回调获取结果。
class TotalError:
def __init__(self):
self.value = 0
def __call__(self, r):
self.value += r.result()
total_error = TotalError()
with futures.ProcessPoolExecutor() as pool:
for i in range(24):
future_result = pool.submit(some_function_call, parameters1, parameters2)
future_result.add_done_callback(total_error)
print(total_error.value)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句