【发布时间】:2021-11-18 06:31:08
【问题描述】:
我想使用 20 毫秒的睡眠时间。当我使用 time.sleep(0.02) 时,我遇到了很多问题。它不符合我的要求。如果我不得不举个例子;
import time
i = 0
end = time.time() + 10
while time.time() < end:
i += 1
time.sleep(0.02)
print(i)
我们等待在控制台中看到“500”。但它就像“320”。这是一个巨大的差异。因为睡眠时间不正确,并且每次睡眠时间都会出现小偏差。它在累积增加,我们看到了错误的结果。
然后,我想为时钟脉冲创建新项目。 time.time() 有可能吗?
import time
first_time = time.time() * 100 #convert seconds to 10 * miliseconds
first_time = int(first_time) #convert integer
first_if = first_time
second_if = first_time + 2 #for sleep 20ms
third_if = first_time + 4 #for sleep 40ms
fourth_if = first_time + 6 #for sleep 60ms
fifth_if = first_time + 8 #for sleep 80ms
end = time.time() + 8
i = 0
while time.time() < end:
now = time.time() * 100 #convert seconds to 10 * miliseconds
now = int(now) #convert integer
if i == 0 and (now == first_if or now > first_if):
print('1_' + str(now))
i = 1
if i == 1 and (now == second_if or now > second_if):
print('2_' + str(now))
i = 2
if i == 2 and (now == third_if or now > third_if):
print('3_' + str(now))
i = 3
if i == 3 and (now == fourth_if or now > fourth_if):
print('4_' + str(now))
i = 4
if i == 4 and (now == fifth_if or now > fifth_if):
print('5_' + str(now))
break
Out >> 1_163255259009
2_163255259011
3_163255259013
4_163255259015
5_163255259017
这个项目是真的逻辑吗?如果是真正的逻辑,如何才能用真正的循环完成这个项目? 因为我希望这些睡眠一直发生。谢谢你的建议。
【问题讨论】:
-
考虑一下,不是一个人睡觉,而是搞砸了。您正在同一个循环中运行一些其他慢速代码,例如打印语句。
标签: python time sleep clock pulse