python - 使用日期时间进行最后一次循环?
问题描述
Stackoverflow 的聪明头脑,我有你的追求。目前我正在运行一个循环,其中发生计算和数据采集。随着时间的推移,这些变得越来越复杂。我希望循环的每次运行都持续一秒钟。由于计算时间的增长,最后一个简单的“sleep(1)”并没有真正的帮助。
while True:
#here calculations happen that take more and more time
print 'some of the data'
sleep(1)
我希望在这些计算之前和之后使用 datetime 来计算秒/毫秒,然后将差异输入到 sleep 命令中。但我无法完全理解它。谁能帮我吗?
a=datetime.now()
#calculations
b=datetime.now()
calctime=(b-a).total_seconds()
sleep(1-calctime)
解决方案
尝试这个:
from datetime import datetime
import time
def test():
a = datetime.now()
# calculations
b = datetime.now()
calctime = (b - a).total_seconds()
print("one")
time.sleep((1 - calctime) if (1-calctime)>0.0 else 0) #if your calculation already took 1 or more than 1 second then then make the waiting time 0
print("two")
test()
推荐阅读
- excel - 需要在excel中转换加3个月
- postgresql - 部分唯一索引不适用于冲突子句 PostgreSQL
- sql - 如果不存在则插入数据的过程 pl sql
- git-p4 - 仓库不同时的 git-p4 克隆
- reactjs - 如果第一个请求返回 400,则 Axios 第二个请求失败并出现 CORS 错误,但如果返回 200,则工作正常
- python-3.x - 在 python 3 中显示链接列表时的特殊输出
- bitbucket - 如何在 bitbucket 上解决这个拉取请求问题?我们不能让你看到这个页面 要访问这个页面
- regex - 在 bash 如何将 extglobed 文件名放入数组中?
- python - 强制编码/数据库使用 asyncpg 而不是 psycopg2
- python - 由于 OpenCV-Python 中 IF 语句的歧义导致的值错误