在给定时间后打破专有工具箱

Del*_*yle 10 matlab timeout break

我每次都在MATLAB中迭代一个大的测试矩阵并调用第二方专有软件(在MATLAB中运行).我无法编辑软件源代码.有时候,软件会挂起,所以我想在一段时间后退出它并继续下一次迭代.

在伪代码中,我这样做:

for i = 1:n
    output(i) = proprietary_software(input(i));
end
Run Code Online (Sandbox Code Playgroud)

output(i)='too_long'如果专有软件耗时太长,我怎样才能跳到下一次迭代(并可能保存)?

Tim*_*ams 1

您需要从 Matlab 的另一个实例调用 Matlab。Matlab 的另一个实例将运行该命令并将控制权释放给 Matlab 的第一个实例,以等待保存结果或达到特定时间。在这种情况下,它将等待 30 秒。

您将需要 1 个附加功能。确保该函数位于 Matlab 路径上。

function proprietary_software_caller(input)
    hTic=tic;
    output=proprietary_software(input);
    hToc=toc(hTic);
    if hToc<30
       save('outfile.mat','output');
    end
    exit;
end
Run Code Online (Sandbox Code Playgroud)

您需要这样修改原始脚本

[status,firstPID] = str2double(system('for /f "tokens=2 delims=," %F in (''tasklist /nh /fi "imagename eq Matlab.exe" /fo csv) do @echo %~F'')'));

for i = 1:n
    inputStr=num2str(input(i));
    system(['matlab.exe -nodesktop -r proprietary_software_caller\(',inputStr,'\)&']);
    hTic=tic;
    hToc=toc(hTic);
    while hToc<30 || ~(exist('outfile.mat','file')==2)
       hToc=toc(hTic);
    end
    if hToc>=30
        output(i)= 'too_long';
        [status,allPIDs]=str2double(system('for /f "tokens=2 delims=," %F in (''tasklist /nh /fi "imagename eq Matlab.exe" /fo csv) do @echo %~F'')'));
        allPIDs(allPIDs==firstPID)=[];
        for a=1:numel(allPIDs)
           [status,cmdout]=system(['taskkill /F /pid ' sprintf('%i',allPIDs(a))]);
        end
    elseif exist('outfile.mat','file')==2
        loadedData=load('outfile.mat');
        output(i)=loadedData.output;
        delete('outfile.mat');
    end
end
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。