0

So what I am trying to do is have a bit of code check the time and at a a given time do something, the current part I am working on is small but I want it to run as efficiently as possible because the program will be running for long amounts of time when its finished. I've noticed on on task manager when I run a file with only the bit of code I will show soon my cpu usage is over 15% with an i7 7700 cpu, is there any way to make this code more efficient?

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
  • 1
    If you don't need extreme precision you can, `import time` and then just put a `time.sleep(1)` after your `while True` this will free the CPU to do other stuff rather than hogging the cpu. See https://stackoverflow.com/questions/18406165/creating-a-timer-in-python You should adjust your time check so it doesn't compare strings but just compares the actual date value. Also you might need to compare a range of time rather than an exact time – User Oct 02 '17 at 08:48

2 Answers2

0

If your program can remain idle until calling the browser, you can use sleep, for the time difference between now and 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')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

15% imho means you have one core filled 100%, because you're continuously looping. You can sleep() for 1+ seconds so the CPU is not busy looping and you need to add a fuzzy comparison for:

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

I'd go for something like:

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

It's a bit convoluted bout you can extend to support multiple alarm times and change the if logic to suit your needs.

Laur Ivan
  • 4,117
  • 3
  • 38
  • 62