Interrupt a while loop with functions if it takes too long

조회 수: 5 (최근 30일)
darwusch darwusch
darwusch darwusch 2024년 9월 24일
댓글: Aquatris 2024년 9월 26일
I have a while loop containing several functions. If one of these functions takes to long, I want to break it.
All solutions that I found do not work because they check the time not continuely during the execution, but at the end of the functions.
Is there a way of timing the iteration during its execution and break it?
I mean with code, not ctrl-c
  댓글 수: 1
Aquatris
Aquatris 2024년 9월 26일
you can also use a timer to check the execution time and provide warning. I am not sure how you would stop execution of a function within a while loop from timer callback. Maybe another global flag can be used. This community loves global variables (!)
global tStart tMax % global variables so they can be reached from timer callback function
tMax = 4; % seconds
% create timer
t = timer;
t.StartDelay = 1;
t.Period = 2;
t.ExecutionMode = 'fixedRate';
t.TimerFcn = @stopExec;
start(t)
cnt = 0;
% dummy while loop
while cnt >=1
tStart = tic;
myFun1;
tStart = tic;
myFun2;
tStart = tic;
myFun3;
cnt = cnt+1;
end
% timer function that gives error
function stopExec(~,~)
global tStart tMax
if isempty(tStart)
tStart = tic;
end
% create warning when time limit it exceeded
funCallStack = dbstack; % get running function stack
if toc(tStart)>=tMax
warning(sprintf('Exceeded Time Limit! @ %s. \n Time limit: %.2f,Current Execution Time: %.2f ',funCallStack(4).name,tMax,(toc(tStart))))
end
end
% dummy functions called from while loop
function myFun1()
pause(5)
end
function myFun2()
pause(8)
end
function myFun3()
pause(3)
end

댓글을 달려면 로그인하십시오.

채택된 답변

Torsten
Torsten 2024년 9월 24일
편집: Torsten 2024년 9월 24일
Is there a way of timing the iteration during its execution and break it?
No. You could go into the function and time certain operations therein. But you always have to wait until the operations are done before getting the chance to stop the code.
  댓글 수: 3
Torsten
Torsten 2024년 9월 24일
Exiting a while loop is usually done by counting the number of times it is executed and exiting if a prescribed maximum number of loops is reached:
nmax = 10;
count = 0;
i = 1;
while count < nmax
i = 2*i;
count = count + 1;
end
i
i = 1024
darwusch darwusch
darwusch darwusch 2024년 9월 24일
No that does not break the iteration during its execution, but after it already finished. That's too late.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

jwiix
jwiix 2024년 9월 24일
function [outputArg1,outputArg2] = yourFunction()
%YOURFUNCTION Summary of this function goes here
% Detailed explanation goes here
outputArg1 = 1;
outputArg2 = 2;
end
function [outputArg1,outputArg2] = yourFunction2()
%YOURFUNCTION Summary of this function goes here
% Detailed explanation goes here
outputArg1 = 1;
outputArg2 = 2;
wait(10);
end
function result = runWithTimeoutSimplified(func, timeout)
% Create a parallel pool if it doesn't exist
if isempty(gcp('nocreate'))
parpool('local', 1);
end
% Start the function asynchronously
f = parfeval(@() func(), 1);
tic;
a=true;
runFlag=0;
while a
b=toc;
a=b<timeout;
% Wait for the function to complete or timeout
if strcmpi(f.State,'running')
runFlag =1;
else
runFlag=0;
[result] = fetchOutputs(f);
break;
end
end
if runFlag
cancel(f);
disp('Operation cancelled due to timeout')
else
disp(result);
end
end
% Then in console:
>> result = runWithTimeoutSimplified(@yourFunction, 5) % This should pass and display result
>> result = runWithTimeoutSimplified(@yourFunction2, 5) % This will fail and be cancelled after timeout .. in this case 5 seconds

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by