how to run a while loop as long as the time parameter input is not exceeded?
조회 수: 25 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!