Python计时器消耗过多的CPU

时间:2016-07-04 10:31:34

标签: python ctypes

当我在任务管理器中签入时,在9小时以上运行时,有时无法提醒它消耗30%或更多的CPU。如果有人可以调整它,那就太好了。

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)     

2 个答案:

答案 0 :(得分:1)

试试这个:

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)   

问题是你的循环中没有sleep(),所以循环字面上每秒运行数百到数千或数万次,占用CPU。上面的代码将在重复循环之前等待1分钟。

如果你在等待计时器时根本不需要做任何事情,你可以完全避免循环而只是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) 

答案 1 :(得分:1)

这不会达到完全相同的目的吗?因为你在循环时没有做任何事情。

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)