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).
这篇关于多处理具有多个输入的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多处理具有多个输入的函数
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
