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

54 views (last 30 days)
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

Answers (1)

arich82
arich82 on 11 Dec 2015
Edited: arich82 on 11 Dec 2015
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 Comment
John
John on 12 Dec 2015
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!

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!