如何剖析运行Keras深度学习模型的Python脚本CPU使用率?
针对Keras模型推理阶段的CPU使用率监控方案
我懂你的痛点——psutil只做前后采样完全没法捕捉模型推理过程中CPU使用率的波动,毕竟推理是个持续的过程,得有能实时追踪或者按阶段统计的工具才行。下面给你几个实用的方案,都是能针对性解决Keras模型推理CPU监控需求的:
1. 基于psutil+线程的实时采样方案
既然你已经熟悉psutil,那可以用它结合线程实现持续采样,精准捕捉推理全程的CPU使用率变化。这种方案灵活可控,完全自定义采样间隔,还能把数据存下来做后续分析。
示例代码:
import psutil import threading import time from keras.models import load_model # 存储CPU使用率的列表(时间戳+使用率百分比) cpu_usage_records = [] _monitor_active = False def cpu_monitor_thread(sample_interval=0.1): """后台线程,持续采样当前进程的CPU使用率""" global _monitor_active current_process = psutil.Process() while _monitor_active: # interval参数控制采样间隔,这里设置为0.1秒 cpu_percent = current_process.cpu_percent(interval=sample_interval) cpu_usage_records.append((time.time(), cpu_percent)) time.sleep(sample_interval) # 加载你的Keras模型和测试数据 model = load_model("your_trained_model.h5") test_input = ... # 你的推理输入数据 # 启动CPU监控 _monitor_active = True monitor_thread = threading.Thread(target=cpu_monitor_thread) monitor_thread.start() # 执行模型推理(重点监控的阶段) inference_results = model.predict(test_input) # 停止监控并等待线程结束 _monitor_active = False monitor_thread.join() # 输出或分析采集到的数据 print("推理阶段CPU使用率变化:") for ts, usage in cpu_usage_records: print(f"时间戳 {ts:.2f}:CPU使用率 {usage}%")
2. py-spy:无侵入式实时CPU采样分析器
py-spy是个不需要修改代码的采样工具,能实时追踪进程的CPU使用情况,还能生成可视化的火焰图,非常适合快速排查推理阶段的CPU热点。
使用方法:
- 先安装py-spy:
pip install py-spy - 在命令行运行你的推理脚本,同时启动py-spy监控:
py-spy record -o inference_cpu_profile.svg -- python your_inference_script.py
执行完成后会生成一个SVG格式的火焰图,你可以用浏览器打开,清晰看到推理过程中各个函数的CPU占用情况和时间分布。
3. line_profiler:行级CPU耗时分析
如果你想精确到代码行的CPU消耗情况(比如想知道模型推理里哪一步最占CPU),line_profiler是个不错的选择。它能统计每一行代码的执行时间,间接反映CPU的使用强度。
示例用法:
- 安装line_profiler:
pip install line_profiler - 给你的推理函数加上装饰器,然后运行分析:
from line_profiler import LineProfiler from keras.models import load_model def run_inference(model, input_data): """封装推理逻辑的函数""" return model.predict(input_data) # 加载模型和数据 model = load_model("your_trained_model.h5") test_input = ... # 初始化分析器并运行 lp = LineProfiler() lp_wrapper = lp(run_inference) lp_wrapper(model, test_input) # 打印行级耗时统计 lp.print_stats()
输出结果会显示每一行代码的执行时间、占总时间的比例,帮你定位推理过程中的CPU密集型代码段。
4. cProfile:标准库内置的CPU性能分析器
Python标准库自带的cProfile可以统计函数调用的CPU时间分布,虽然不是实时的使用率,但能帮你了解推理阶段各个函数的CPU消耗占比,适合做整体性能分析。
使用方法:
直接在命令行运行脚本时加上cProfile参数:
python -m cProfile -s cumulative your_inference_script.py
或者在代码中嵌入分析逻辑:
import cProfile from keras.models import load_model model = load_model("your_trained_model.h5") test_input = ... def main(): model.predict(test_input) cProfile.runctx("main()", globals(), locals(), "inference_profile.stats")
之后可以用pstats模块读取生成的stats文件,分析函数的CPU耗时情况。
内容的提问来源于stack exchange,提问作者Philip O'Brien
相关产品推荐
相关产品推荐

