您可以使用Python的多处理程序包实现基于进程的并行。
下面是使用池的Gurobi 9的一些示例代码:
将多处理作为mp导入
导入gurobipy作为gp
def解算模型(输入数据):
将gp.Env()作为环境,将gp.Model(Env=Env)作为模型:
#定义模型
model.optimize()
#从模型中检索数据
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
使用mp.Pool()作为池:
map(求解_模型,[input_data1,input_data2,input_data3]
请注意,基于线程的并行性(例如使用线程模块)是不可能因为当前gurobipy模块不是线程安全的。
环境
使用多处理时,每个进程都应该创建自己的环境。另外,请注意,您应该确保正确关闭您的环境并处置您的模型。从Gurobi 9开始,您可以使用以下模式,在离开with块时自动放弃您的模型和环境:
使用gp.Env()作为环境,gp.Model(Env=Env)作为模型:#剩余的模型代码
对于Gurobi 8及更早版本,您必须使用:
env=gp.env()
模型=总模型(环境=环境)
#剩余型号代码
del模型
德尔恩夫
macOS 10.13及更高版本的问题
多处理程序包支持启动子进程的不同方法。在Python3.7之前,macOS上的默认方法是forking。但是,在macOS 10.13及更高版本上,存在一些问题:没有exec的Fork可能会使子进程崩溃;看见在这里. 在这种情况下,应该使用“spawn”。要改变这一点,您可以使用
mp.set\u start\u方法(“生成”)
全局更改设置。或使用
使用mp.get_context(“spawn”).Pool()作为池:
# ...
仅为一个池更改它。
从Python3.8开始,生成已经是macOS上的默认设置。
看见在这里了解更多信息。
关键词:
优化异步