首页 > 解决方案 > 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?

标签: pythonfor-loopwhile-looptimeit

解决方案


你可以这样做:

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  

只要在您设置的时间限制之后达到迭代结束,该break语句就会退出循环。


推荐阅读