Jake Jake - 4 months ago 22
Python Question

Python Timer consuming too much cpu

Running below sometimes fails to alert after 9 hours and more over it's consuming 30% or more CPU, when I check in Task Manager. If anyone can tweak this it would be great.

import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
elapsed = elapsed//60
ctypes.windll.user32.MessageBoxA(0,"Done "+str(elapsed) + " Hrs", "Done", 0)
timer(8)

Answer

Try this:

import time
import ctypes

def timer(hours):
    seconds = hours * 3600
    start = time.time()

    elapsed = 0
    while elapsed < seconds:
        # Do something once every minute.
        time.sleep(60)
        elapsed = time.time() - start

    elapsed = elapsed//60

    ctypes.windll.user32.MessageBoxA(0,"Done "+str(elapsed) + " Hrs",  "Done", 0)

timer(8)   

The problem is that you don't sleep() in your loop, so the loop literally just runs many hundreds to thousands or tens of thousands of times per second, eating CPU. The code above will wait 1 minute before repeating the loop.

If you don't need to do anything at all while waiting on the timer, you can avoid the loop entirely and just sleep():

import time
import ctypes

def timer(hours):
    time.sleep(hours * 3600)
    ctypes.windll.user32.MessageBoxA(0,"Done "+str(hours) + " Hrs",  "Done", 0)

timer(8) 
Comments