Python定时器消耗太多CPU

标签 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)     

最佳答案

试试这个:

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) 

关于Python定时器消耗太多CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38182529/

相关文章:

python - 从内存地址创建 python 对象(使用 gi.repository)

python - 错误的 ctypes 分配

Python模型继承和模型声明的顺序

python - 为什么 CherryPy 静态文件下载这么慢?

python - : Python, ctypes.windll.user32.SystemParametersInfoA 中的参数是什么?

python - 使用 Ctypes 和 Python.h 将列表从 Python 传递到 C

python - 使用 Ctypes 从 Python 传递 C 结构

python - Windows 10 上的 TensorFlow : “not a supported wheel on this platform” error

python - 为什么更新一个字典对象会影响其他对象?

python - 投资组合优化的蒙特卡罗方法