使用日期时间使循环持续一秒?



Stackoverflow的聪明头脑,我有一个任务要找你。 目前,我正在运行一个循环,其中进行计算和数据采集。随着时间的推移,这些变得越来越复杂。我希望循环的每次运行都持续一秒钟。由于计算时间的增加,最后的简单"sleep(1("并没有真正的帮助。

while True:
#here calculations happen that take more and more time
print 'some of the data'
sleep(1)

我希望使用日期时间来计算这些计算之前和之后的秒/毫秒,以便在睡眠命令中输入差异。但我无法完全理解它。谁能帮我?

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()
a=datetime.now()
#calculations
b=datetime.now()
calctime=b-a
ms = calctime.microseconds
if calctime.seconds == 0:
sleep(1-ms/1000000)

此处的其他信息:Python 速度测试 - 时差 - 毫秒

最新更新