You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python对比新旧CPU使用率失效问题求助

问题分析与修复方案

核心问题

你的代码每次都执行第一个if分支,根源是**old_cpu_usage被定义在while循环内部**——每次循环都会把它重置为0,导致old_cpu_usage == 0永远为真,永远触发首次运行的逻辑。

其他需要修正的问题

除了作用域问题,代码还有几个不符合需求的地方:

  • 循环间隔是2秒,不符合“每20秒检查”的要求
  • 涨幅计算公式错误:当前((cpu_usage_percent - old_cpu_usage )/cpu_usage_percent * 100是相对于新值的比例,正确的涨幅应该是相对于旧值的((新值 - 旧值)/旧值)*100
  • 进程判断用了memory_percent(内存使用率),但需求是输出**CPU占用率超过1%**的进程

修复后的完整代码

import psutil   
import time   

status = 'start'
old_cpu_usage = None  # 初始设为None,用于标记首次运行

while status != 'stop':
    # 获取当前CPU使用率,interval=1表示采样1秒的平均使用率
    cpu_usage_percent = psutil.cpu_percent(interval=1, percpu=False) 

    print()

    if old_cpu_usage is None:
        # 首次运行逻辑
        print(f"The CPU usage is {cpu_usage_percent}%")
        old_cpu_usage = cpu_usage_percent
    else:
        # 计算涨幅(相对于旧值的百分比)
        try:
            increase_rate = ((cpu_usage_percent - old_cpu_usage) / old_cpu_usage) * 100
        except ZeroDivisionError:
            # 处理旧值为0的特殊情况
            increase_rate = float('inf') if cpu_usage_percent > 0 else 0

        if increase_rate > 9:
            print(f"CPU usage increased significantly (from {old_cpu_usage}% to {cpu_usage_percent}%, +{increase_rate:.1f}%)")
            print("Processes with CPU usage over 1%:")
            # 遍历进程,获取CPU使用率
            for process in psutil.process_iter(['name', 'cpu_percent']):
                try:
                    p_info = process.info
                    cpu_percent = p_info['cpu_percent']
                    if cpu_percent > 1:
                        print(f"- {p_info['name']}: {cpu_percent}% CPU")
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    # 跳过已结束或无权限访问的进程
                    continue
        else:
            print(f"The CPU usage did not increase significantly, current usage: {cpu_usage_percent}%")
        
        # 更新旧值为当前值
        old_cpu_usage = cpu_usage_percent
    
    # 每20秒检查一次
    time.sleep(20)

关键修改说明

  1. old_cpu_usage移到循环外:确保每次循环能保留上一次的CPU使用率值,不会被重置
  2. 修正循环间隔:把time.sleep(2)改成time.sleep(20),符合需求
  3. 修复涨幅计算:改用相对于旧值的比例计算,同时处理旧值为0的异常情况
  4. 修正进程CPU使用率获取:使用cpu_percent字段替代memory_percent,并通过指定字段列表优化process_iter的性能,同时捕获进程不存在或无权限的异常
  5. 首次运行标记优化:用None作为初始值,比0更清晰区分首次运行和CPU使用率为0的情况

内容的提问来源于stack exchange,提问作者Opeyemi Odedeyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:40:29