How to know elapsed time during execution of system command in Matlab?

怎甘沉沦 提交于 2020-02-25 02:09:05

问题


I have a Matlab code that runs a system script. The script may be stopped due to the command runs. I want to know if there is a way that the program knows if it has taken a long time and do something else. Here is the code:

tic;
[status,cmdout]=system(iperfcmd); % The program can be blocked here
toc; % I want to know if it has taken a long time (like 5 seconds) for the system call and kill it. 

回答1:


How about performing the system call asynchronously (https://uk.mathworks.com/help/parallel-computing/parallel.pool.parfeval.html) and polling from the main thread, something like this:

% Setup
tMax = 5;         % Maximum time to wait for system call
pollDelay = 1;    % Time between polls
timeOut = false;
% Run system call asynchronously
F = parfeval(@timeSystem,3,'iperfcmd');
tic
% Poll at regular intervals, break out if it finishes or exceeds time limit 
while strcmp(F.State,'running') && ~timeOut
    t = toc;
    pause(pollDelay)
    if t>tMax 
        timeOut = true; % This terminates the loop (alternatively use break)
    end
end

if strcmp(F.State,'finished')
    [status,cmdout,runTime]=fetchOutputs(F);
else
    % Handle hanging system call here
    cancel(F) % Cancelling the FutureEvent might terminate the system call?
end

function [status,cmdout,runTime] = timeSystem(command)
tStart = tic;
[status,cmdout] = system(command)
runTime = toc;
end

Hopefully that works for you. It's untested tested due to not having iperfcmd




回答2:


Assign toc to a variable and then do logic on that value

tic
[status,cmdout]=system(iperfcmd);
elapsedTime = toc;

elapsedTime > 5


来源:https://stackoverflow.com/questions/60101154/how-to-know-elapsed-time-during-execution-of-system-command-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!