how to run a while loop as long as the time parameter input is not exceeded?

조회 수: 25 (최근 30일)
John
John 2015년 12월 11일
댓글: John 2015년 12월 12일
Hi guys,
i would like to run a heuristic algorithm calculating better solutions over time... and i would like the user to tell how long the programm shall run and then return the best solution found within this time.
How can i realize it with a while loop over the time...in pseudo-code it shall look like this:
while running_time_of_the_algorithm < user_input_time
....calculating solutions and overwriting them in the variable " best_solution "
end
% here i can just access the best solution after exceeding the time
final_solution=best_solution
i know how that measuring time can be done using the commands "tic" and "toc" ... is it realizable with them or are there any other efficient solutions?
i would be very glad for your help!
best regards,
john

답변 (1개)

arich82
arich82 2015년 12월 11일
편집: arich82 2015년 12월 11일
There are probably more elegant solutions using timer objects, but if the code is reasonably simple (no single function takes too much time, no parfor), then you can get a quick-and-dirty solution using tic and toc:
user_input_time = 3;
count = 0; count_max = 1e9;
tic;
while (toc < user_input_time) && (count < count_max) % always include a failsafe!
count = count + 1;
end
disp(count);
Again, this is only reasonable if the while loop cycles quickly; if you specify 5 seconds but each loop takes 4 seconds, it won't kick out until 8 seconds have passed (i.e. the next time toc is evaluated).
(Incidentally, my computer returns 7558253 after 3 seconds.)
Please accept this answer if it helps, or let me know in the comments if your situation requires a more nuanced timing loop.
  댓글 수: 1
John
John 2015년 12월 12일
Hi arich82,
thank you very much for your answer! indeed the while loop in my programm can take lots of time...and the time it needs in every run is not deterministic..thats why your solution would not be that suitable! nevertheless, thank you very much!

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by