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

34 visualizaciones (últimos 30 días)
John
John el 11 de Dic. de 2015
Comentada: John el 12 de Dic. de 2015
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

Respuestas (1)

arich82
arich82 el 11 de Dic. de 2015
Editada: arich82 el 11 de Dic. de 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 comentario
John
John el 12 de Dic. de 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!

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by