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!