How do I wait for a function to complete in some stipulated time or move on?
4 次查看(过去 30 天)
显示 更早的评论
I have two functions A and B. I want to run B after A but only if A completes execution within 10 secs. In case A is taking more than 10 secs then I would like to move on with B.
How do i achieve this?
I have tried following and am looking for a better approach.
counter = 0;
% A_resp - bool returned by A when finished
while ( ~A_resp && counter < 100)
pause(0.1);
counter = counter + 1;
end
% B is here
3 个评论
Walter Roberson
2020-4-4
cputime() and clock() can only work with the cooperation of the function being called: the function itself has to volunteer to give up control after the time limit.
Aaron Pedersen
2020-4-4
Yes, the more I look into this the more I realize that this is beyond my skill in matlab. Many thanks.
回答(1 个)
Walter Roberson
2020-4-4
MATLAB has some undocumented method of restricting CPU time that it uses for MATLAB Online and for Cody. I have not been able to figure out yet how it does that.
Aaron Pedersen suggests using cputime() or clock() within the function to test whether it has reached its limit yet. That works okay for functions that deliberately cooperate... and which do not accidentally get stuck on something while they are not checking time... and which do not end up buried inside LAPACK or symbolic toolbox or similar that do not check timed or otherwise cooperate on being limited.
The only documented way of limiting time on something that is not actively cooperating (and is not getting stuck), is to use Parallel Computing Toolbox to create a "future" such as by parfeval() to evaluate the task in a separate process, and to monitor the status, because futures can be cancel()'d while they are executing.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!