【问题标题】:Running n MATLAB instances using python in parallel使用 python 并行运行 n 个 MATLAB 实例
【发布时间】:2020-04-17 04:30:24
【问题描述】:

我想在 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

有谁知道我如何同时做类似的事情?

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

编辑/添加了 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

【问题讨论】:

    标签: python matlab


    【解决方案1】:

    start_matlab 函数 here 的 MATLAB 文档说:

    每次调用 matlab.engine.start_matlab 时,它都会启动一个新的 MATLAB 进程。

    因此,为每个测试启动一个新的 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 个,则可能值得使用循环来执行此操作。

    【讨论】:

    • 谢谢 Dominic D .. 我现在就试试看。
    • 嗨多米尼克..它工作...感谢您的输入..快速提问。函数'runTest1.m'会导致错误/键盘情况(测试函数中有错误和键盘,它们确实在某些输入上调用),我需要知道这种情况是否发生在python中......我尝试使用stdout = test1_future 行中的 out 和 stderr=err 并尝试获取 err.getvalue() ,但即使发生错误也不会打印
    • mathworks.com/help/matlab/matlab_external/… .. 这就是我所遵循的 out=io.StringIO() err=io.StringIO() test1_future = eng1.runTest1(1,nargout=1,stdout=out,stderr=错误,背景=真)
    • 我想我有一个捕获错误的解决方案...我正在使用 test1_future .cancelled() 并且当发生任何错误时这将是 TRUE...现在,我正在尝试捕获键盘
    • 键盘是否意味着您正在尝试捕获控制台输出? (运行该函数时您会在 matlab 控制台中看到什么)或者尝试捕获诸如键盘中断之类的东西?
    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2011-04-30
    • 2021-02-01
    • 1970-01-01
    • 2015-04-24
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多