首页 > 解决方案 > 使用日期时间进行最后一次循环?

问题描述

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)

标签: pythonloopsdatetimesleep

解决方案


尝试这个:

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()

推荐阅读