Search code examples
pythonfor-loopwhile-looptimeit

How to end a for loop after a given amount of time


I execute my code in a loop for many objects and it seems that process too much time.

I would like to add a condition that stops the execution after 30 min for example. How should it be done? Do I need another for loop and the timeit module for that or it can be done easier?


Solution

  • You can do it with something like this:

    import time
    
    time_limit = 60 * 30 # Number of seconds in one minute
    t0 = time.time()
    for obj in list_of_objects_to_iterate_over:
        do_some_stuff(obj)   
        if time.time() - t0 > time_limit:
            break  
    

    The break statement will exit the loop whenever the end of your iteration is reached after the time limit you have set.