简体   繁体   English

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

[英]Running n MATLAB instances using python in parallel

I would like to run some tests on MATLAB which usually takes 2 days and I have 3 such tests( so 3 x 2 = 6 days ).我想在 MATLAB 上运行一些测试,这通常需要 2 天,我有 3 个这样的测试(所以 3 x 2 = 6 天)。 So, I run three MATLAB sessions on my windows machine and run my three tests (in parallel) which reduces my test time from 6 days to 2 days.因此,我在 windows 机器上运行了三个 MATLAB 会话并运行了三个测试(并行),这将我的测试时间从 6 天减少到 2 天。

I would like to do similar stuff on python to invoke three MATLAB instances.(I can do that serially, but not parallely)我想在 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

Does anyone know how I can do similar stuff in parallel?有谁知道我可以如何并行做类似的事情?

Please let me know if you have any questions/suggestions/comments?如果您有任何问题/建议/意见,请告诉我?

EDITED/Added the runTest1 skeleton编辑/添加了 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

The MATLAB documentation for the start_matlab function here says: start_matlab function 的 MATLAB 文档在这里说:

Each time you call matlab.engine.start_matlab, it starts a new MATLAB process.每次调用 matlab.engine.start_matlab 时,都会启动一个新的 MATLAB 进程。

So, start a new MATLAB process for each test, and run them all.因此,为每个测试启动一个新的 MATLAB 进程,并运行它们。 We also find from the documentation here that we need to use the background=True argument when running functions so that Python can call all 3 tests without waiting for them to finish.我们还从此处的文档中发现,我们需要在运行函数时使用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...

If you had a lot more than 3 it would probably be worth doing this with a loop.如果您的数量超过 3 个,则可能值得使用循环来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM