【问题标题】:most efficient way to check for a specific time检查特定时间的最有效方法
【发布时间】: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 您应该调整时间检查,使其不比较字符串,而只比较实际日期值。此外,您可能需要比较时间范围而不是确切时间

标签: python datetime


【解决方案1】:

如果您的程序在调用浏览器之前可以保持空闲状态,您可以使用 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')

【讨论】:

    【解决方案2】:

    恕我直言,15% 意味着你有一个核心 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 逻辑以满足您的需求,这有点令人费解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      相关资源
      最近更新 更多