使用日期时间使循环持续一秒?
Make a loop last once second using datetime?
Whosebug 的聪明头脑,我有一个任务要找你。
目前我正在 运行 循环中进行计算和数据采集。随着时间的推移,这些变得越来越复杂。我希望循环的每个 运行 只持续一秒钟。由于计算时间的增长,最后一个简单的 "sleep(1)" 并没有真正帮助。
while True:
#here calculations happen that take more and more time
print 'some of the data'
sleep(1)
我希望在这些计算之前和之后使用 datetime 来计算 seconds/milliseconds 以将差异输入睡眠命令。但我不能完全理解它。谁能帮帮我?
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 speed testing - Time Difference - milliseconds
Whosebug 的聪明头脑,我有一个任务要找你。 目前我正在 运行 循环中进行计算和数据采集。随着时间的推移,这些变得越来越复杂。我希望循环的每个 运行 只持续一秒钟。由于计算时间的增长,最后一个简单的 "sleep(1)" 并没有真正帮助。
while True:
#here calculations happen that take more and more time
print 'some of the data'
sleep(1)
我希望在这些计算之前和之后使用 datetime 来计算 seconds/milliseconds 以将差异输入睡眠命令。但我不能完全理解它。谁能帮帮我?
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 speed testing - Time Difference - milliseconds