python - 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?
解决方案
你可以这样做:
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
语句就会退出循环。
推荐阅读
- c++ - Emscripten:如何为 C++ 数组类型定义 webidl
- java - Java/Kotlin Android 应用的通用应用状态架构?
- javascript - 当我使用 ip:port 时 getUserMedia 未定义
- python - 如何使用指定的 ca 文件通过 ssl 执行 get 请求
- kotlin - 如何在 Kotlin 中实现域实体?
- ios - 使用虚拟对象捕获 ARSCNView - iOS
- c++ - 如何为链表创建复制构造函数?
- java - 如何计算多个数组中所有元素的频率?
- python - 更改链接到标签的变量后如何更新 Tkinter 标签?
- swift - UIButton 不会指向目标