Multiprocessing a function with several inputs(多处理具有多个输入的函数)
问题描述
在 Python 中,multiprocessing
模块可用于在一系列值上并行运行函数.例如,这会生成 f 的前 100000 次评估的列表.
In Python the multiprocessing
module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.
def f(i):
return i * i
def main():
import multiprocessing
pool = multiprocessing.Pool(2)
ans = pool.map(f, range(100000))
return ans
当 f 接受多个输入但只有一个变量变化时,是否可以做类似的事情?例如,您将如何并行化:
Can a similar thing be done when f takes multiple inputs but only one variable is varied? For example, how would you parallelize this:
def f(i, n):
return i * i + 2*n
def main():
ans = []
for i in range(100000):
ans.append(f(i, 20))
return ans
推荐答案
有几种方法可以做到这一点.在问题中给出的示例中,您可以只定义一个包装函数
There are several ways to do this. In the example given in the question, you could just define a wrapper function
def g(i):
return f(i, 20)
并将这个包装器传递给 map()
.更通用的方法是有一个包装器,它接受一个元组参数并将元组解包为多个参数
and pass this wrapper to map()
. A more general approach is to have a wrapper that takes a single tuple argument and unpacks the tuple to multiple arguments
def g(tup):
return f(*tup)
或使用等效的 lambda 表达式:lambda tup: f(*tup)
.
or use a equivalent lambda expression: lambda tup: f(*tup)
.
这篇关于多处理具有多个输入的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多处理具有多个输入的函数


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01