【发布时间】:2017-10-02 08:39:26
【问题描述】:
所以我要做的是有一些代码检查时间并在给定时间做某事,我正在处理的当前部分很小,但我希望它尽可能高效地运行,因为程序会完成后运行很长时间。我在任务管理器上注意到,当我运行一个只有一点代码的文件时,我很快就会显示我的 cpu 使用率在 i7 7700 cpu 上超过 15%,有什么办法可以让这个代码更有效率吗?
import datetime
import webbrowser
#loop to run until desired time
while True:
#checks current time to see if it is the desired time
if str(datetime.datetime.now().time()) == "11:00:00":
#opens a link when its the desired time
webbrowser.open('https://www.youtube.com/watch?v=q05NxtGgNp4')
break
【问题讨论】:
-
如果您不需要极高的精度,您可以使用
import time,然后在您的while True之后放置一个time.sleep(1),这将释放CPU 做其他事情而不是占用CPU。请参阅stackoverflow.com/questions/18406165/creating-a-timer-in-python 您应该调整时间检查,使其不比较字符串,而只比较实际日期值。此外,您可能需要比较时间范围而不是确切时间