【发布时间】:2020-12-02 02:35:10
【问题描述】:
尝试在特定时间执行函数时遇到问题。
我的想法是我有一个随机时间的 while 循环,在这段时间里,我需要在随机生成的时间执行 50 毫秒的哔声,然后重新分配它(理论上可以调用1-3次)。
如何确保准确计时? 现在我用过:
random_time_loop = np.round(np.random.uniform(4,7), 3)
random_time_tone = np.round(np.random.uniform(2,3), 3)
print("Random_time: {}; random_time_tone: {}".format(random_time_loop, random_time_tone))
t_end = (datetime.datetime.now() + datetime.timedelta(seconds=random_time_loop)).time()
t_tone = (datetime.datetime.now() + datetime.timedelta(seconds=random_time_tone)).time()
print("current: "+str(datetime.datetime.now().time()))
print("t_end: "+ str(t_end))
print("t_ring: "+ str(t_tone))
while datetime.datetime.now().time() < t_end:
if(datetime.datetime.now().time() == t_tone):
print("Ring ring")
print(str(datetime.datetime.now().time()) + "==" + str(t_tone))
random_time_tone = np.round(np.random.uniform(2,3), 3)
t_tone = (datetime.datetime.now() + datetime.timedelta(seconds=random_time_tone)).time()
print("New tone random time: {} ringing at: {}".format(random_time_tone, t_tone))
print("ended: {}".format(datetime.datetime.now().time()))
这个实现的输出:
Random_time: 5.684; random_time_tone: 2.909
current: 12:32:36.713071
t_end: 12:32:42.397056
t_ring: 12:32:39.622069
Ring ring
12:32:39.622101==12:32:39.622069
New tone random time: 2.663 ringing at: 12:32:42.285198
ended: 12:32:42.397059
可以看出,当前时间与函数执行时间并不完全相同。此外,它计划在 *42.285198 响铃,但即使进程在 *42.397059 结束,它也没有发生。是否有可能以毫秒级的精度确保准确执行?我检查了其他一些解决方案,但其中大多数都尝试偶尔执行某些操作,并且不会在如此波动的时间范围内操作。
PS。我知道执行代码时会有一点延迟,因此 datetime.now() 可能会有所不同,尤其是在声明 t_end 和 t_tone 时(可能是一个糟糕的实现,而是使用分配给它的相同当前时间的单个“current_time”变量)。然而,在比较时间时如何确保毫秒精度。
提前谢谢你!
【问题讨论】:
标签: python numpy datetime time