python - Python中的简单并行过程
问题描述
我有一个(非常)简单的过程可以多次执行,大致如下:
import time
class Shop:
def __init__(self):
time.sleep(1.)
self.sale_price = 0
def update(self, weight, price):
self.sale_price = weight * price
my_list = [Shop() for _ in range(20)] #20 shops
weight, price = 2, 3
for o in my_list:
o.update(weight, price)
(函数update
改变 的内部状态o
,没有任何返回值)
我的问题:让这个循环/进程并行运行的简单方法是什么?
我在这里看到了许多并行数学运算(例如矩阵运算)的示例,但我无法让它们适用于我的简单示例。我正在使用 Python 3.6.5
解决方案
找到了一个简单的解决方案:
import time
from joblib import Parallel, delayed
import multiprocessing
class Shop:
def __init__(self):
time.sleep(1.)
self.sale_price = 0
def update(self, weight, price):
self.sale_price = weight * price
my_list = [Shop() for _ in range(20)] #20 shops
weight, price = 2, 3
### Non-parallel
for o in my_list:
o.update(weight, price)
### Parallel
#Helper function (doesn't take weight/price parameters - assumes these are already defined)
def update2(o):
o.update(weight, price)
return o
num_cores = multiprocessing.cpu_count()
my_list = Parallel(n_jobs=num_cores)(delayed(update2)(o) for o in my_list)
我意识到这my_list
最终会重新分配,但这对我的目的来说很好。
推荐阅读
- reporting-services - SSRS visual studio asking credentials while Deploying reports
- excel - "This Action Won't Work on Multiple Selections" - VBA to deselect anything that would be causing the issue?
- c# - How do I add a TreeNode ToolTip delay in c#
- mips - MIPS 如何将浮点数乘以整数并将其存储为浮点数?
- c# - 为什么VSCode的C#扩展找不到dotnet?
- aem - ditamap 中主题引用的数量是否有限制
- c - 杀死任一线程并退出进程
- sql - 带有条件过滤器的 Oracle 查询
- python - 即使在导入 types-python-dateutil 之后,mypy 也找不到 python-dateutil
- c# - 部署的 Azure 函数缺少实体框架 .edmx 文件 - FileNotFoundException