简体   繁体   中英

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)     

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) 

Wouldn't this achieve the exact same thing? Since you are not doing anything while looping anyways.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM