使用python并行运行n个MATLAB实例

2024-09-30 04:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在MATLAB上运行一些测试,通常需要2天,我有3个这样的测试(所以3 x 2=6天)。 因此,我在我的windows机器上运行了三个MATLAB会话,并运行了三个测试(并行),这将我的测试时间从6天减少到了2天

我想在python上做类似的事情来调用三个MATLAB实例。(我可以串行地做,但不能并行地做)

import matlab.engine as MAT_E
eng=MAT_E.start_matlab()

test_id=1
isTestDone = eng.runTest1(test_id,nargout=1)   # runTest1 is a .m file which needs to be run

test_id=2
isTestDone = eng.runTest2(test_id,nargout=1)   # runTest2 is a .m file which needs to be run

test_id=3
isTestDone = eng.runTest3(test_id,nargout=1)   # runTest3 is a .m file which needs to be run

有人知道我怎么能同时做类似的事情吗

如果您有任何问题/建议/意见,请告诉我

编辑/添加了runTest1骨架

function out1 = runTest1(test_id)

% some processing happens and variable 'x' is generated 

if x < 0.1
    % some warning
    warning('the samples are incosistent')
    keyboard;
end

if x > 99
    error('simulation encountered some out of bound values')
end


# some more processing 

end

Tags: toruntestidwhichissomebe
1条回答
网友
1楼 · 发布于 2024-09-30 04:29:42

start_matlab函数here的MATLAB文档说明:

Each time you call matlab.engine.start_matlab, it starts a new MATLAB process.

因此,为每个测试启动一个新的MATLAB过程,并运行它们。我们还从文档here中发现,在运行函数时需要使用background=True参数,以便Python可以调用所有3个测试,而不必等待它们完成

import matlab.engine as MAT_E
eng1 = MAT_E.start_matlab()
eng2 = MAT_E.start_matlab()
eng3 = MAT_E.start_matlab()

# start running the tests
test1_future = eng1.runTest1(1,nargout=1,background=True)
test2_future = eng2.runTest2(2,nargout=1,background=True)
test3_future = eng3.runTest3(3,nargout=1,background=True)

# get the results of all the tests (waits for tests to finish)
result1 = test1_future.result()
result2 = test2_future.result()
result3 = test3_future.result()

# do something with the results...

如果你有很多超过3个,那么用一个循环来做这件事可能是值得的

相关问题 更多 >

    热门问题