python 获取系统CPU和memory

本文档展示了如何使用Python的psutil库获取系统的内存使用百分比和CPU占用情况,提供了getMemCpu函数的详细实现,帮助读者理解基础系统监控技巧。
def getMemCpu(self):
    data = psutil.virtual_memory()
    total = data.total  # 总内存,单位为byte
    free = data.available  # 可以内存
    memory = "Memory usage:%d" % (int(round(data.percent))) + "%" + " "
    cpu = "CPU:%0.2f" % psutil.cpu_percent(interval=1) + "%"
    return memory + cpu
### 结合 `cProfile` `memory_profiler` 分析 CPU 与内存瓶颈 在 Python 程序中,性能瓶颈可能同时涉及 CPU 时间内存使用。为了全面分析程序性能,可以结合 `cProfile` `memory_profiler` 工具,分别定位 CPU 执行瓶颈内存消耗热点。 #### 安装依赖工具 要使用 `cProfile` `memory_profiler`,需先安装 `memory_profiler`: ```bash pip install memory_profiler ``` `cProfile` 是 Python 标准库的一部分,无需额外安装。 #### 使用 `cProfile` 分析 CPU 性能 `cProfile` 可以记录函数调用的时间分布,适用于识别 CPU 密集型操作。以下是一个使用 `cProfile` 分析函数执行时间的示例: ```python import cProfile def example_function(): sum(range(1000000)) cProfile.run('example_function()') ``` 运行结果会显示每个函数的调用次数、总时间、平均时间等信息,帮助识别 CPU 耗时最多的函数。 #### 使用 `memory_profiler` 分析内存消耗 `memory_profiler` 可以逐行分析函数的内存使用情况,适用于识别内存泄漏或高内存消耗的代码段。使用时需在目标函数上添加 `@profile` 装饰器,并通过 `mprof` 命令运行程序: ```python from memory_profiler import profile @profile def example_function(): a = [1] * (10**6) b = [2] * (2 * 10**7) del b return a example_function() ``` 运行命令: ```bash mprof run example_script.py ``` 该命令会生成两个文件:`.dat` 文件用于绘制内存曲线,`.log` 文件记录每一行的内存使用情况。查看内存使用曲线: ```bash mprof plot ``` #### 同时运行 `cProfile` 与 `memory_profiler` 可以将 `cProfile` 与 `memory_profiler` 结合使用,以获得 CPU 时间与内存消耗的完整视图。例如,可以将 `cProfile` 的输出与 `memory_profiler` 的日志同步分析: ```python import cProfile from memory_profiler import profile @profile def example_function(): a = [1] * (10**6) b = [2] * (2 * 10**7) del b return a profiler = cProfile.Profile() profiler.enable() example_function() profiler.disable() profiler.print_stats(sort='time') ``` 运行上述代码后,可分别查看 CPU 时间分布内存使用情况,从而综合判断性能瓶颈。 #### 可视化与结果分析 `cProfile` 的输出可以通过 `pstats` 模块排序过滤,也可以使用 `snakeviz` 工具进行可视化分析: ```bash pip install snakeviz python -m cProfile -o output.prof example_script.py snakeviz output.prof ``` `memory_profiler` 的 `.dat` 文件可以通过 `mprof plot` 命令生成内存使用曲线图,帮助识别内存峰值增长趋势。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值