检查特定时间的最有效方法

时间:2017-10-02 08:39:26

标签: python datetime

所以我要做的是有一些代码检查时间,并在给定时间做一些事情,我正在处理的当前部分很小但我希望它尽可能高效地运行,因为程序将完成后会运行很长时间。我在任务管理器上注意到当我运行一个只带有一点代码的文件时,我很快就会看到我的cpu使用率超过15%使用i7 7700 cpu,有没有办法让这个代码更有效率?

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

2 个答案:

答案 0 :(得分:0)

如果您的程序在调用浏览器之前可以保持空闲状态,则可以使用sleep,以查看现在与11:00:00之间的时差:

import datetime
import webbrowser

# loop to run until desired time

def find_time_between_now__and_11():
    """returns the time in ms between now and 11"""
    return datetime.datetime.now().time() - 11  # pseudocode, you need to figure out how to do that

lag = find_time_between_now__and_11()
time.sleep(lag)

# opens a link when its the desired time
webbrowser.open('https://www.youtube.com/watch?v=q05NxtGgNp4')

答案 1 :(得分:0)

15%imho意味着你有一个核心填充100%,因为你不断循环。您可以sleep() 1秒以上,因此CPU不忙于循环,您需要添加模糊比较:

str(datetime.datetime.now().time()) == "11:00:00"

我会选择类似的东西:

def run_task(alarm):
    last_run = None

    while True:
       now = datetime.datetime.now()
       if now > alarm && last_run != now:
           last_run = now
           # Do whatever you need
           webbrowser.open('https://www.youtube.com/watch?v=q05NxtGgNp4')

       time.sleep(10) # Sleep 10 seconds

您可以扩展以支持多个闹钟时间并更改if逻辑以满足您的需求,这有点令人费解。