python - 如何分析 Python 脚本的 CPU 使用率?

标签 python keras profiling cpu-usage

理想情况下,我想要记录执行深度神经网络的 Python 脚本的 CPU 使用情况 Keras模型。我正在寻找相当于 memory_profiler 的 CPU ,它提供了一个进程的内存消耗。

我看过使用 psutil (在 this answer 中建议)这表明我的脚本可能包含一些变体

p = psutil.Process(current_pid)
p.cpu_percent()

但问题是我真正想要捕获的重要函数调用将是模型的推理阶段

model.predict(x_test)

如果我在此步骤之前/之后运行 psutil,记录的 CPU 使用率将不会真实反射(reflect)进程的 CPU 使用率。

然后我在想我是否可以使用 top/htop 之类的东西将脚本的 CPU 使用情况记录到某个文件中,从而捕获进程中波动的 CPU 使用情况 正在运行,然后在事后计算平均值(或类似的值)。然而,我看到的问题是我不需要知道 PID 就可以使用 top, 那么如何在脚本执行之前使用 top 来监视脚本(甚至还没有分配 PID)?

我可以看到 this highly-ranked answer建议 cProfile 给出脚本中函数的运行时间。虽然这不是我想要的,但我确实注意到它返回了 CPU 总秒数,至少可以让我比较这方面的 CPU 使用率。

最佳答案

您可以在子进程中运行 model.predict(x_test) 并在主进程中同时记录其 CPU 使用率。例如,

import time
import multiprocessing as mp
import psutil
import numpy as np
from keras.models import load_model

def run_predict():
    model = load_model('1.h5')
    x_test = np.random.rand(10000, 1000)
    time.sleep(1)

    for _ in range(3):
        model.predict(x_test)
        time.sleep(0.5)

def monitor(target):
    worker_process = mp.Process(target=target)
    worker_process.start()
    p = psutil.Process(worker_process.pid)

    # log cpu usage of `worker_process` every 10 ms
    cpu_percents = []
    while worker_process.is_alive():
        cpu_percents.append(p.cpu_percent())
        time.sleep(0.01)

    worker_process.join()
    return cpu_percents

cpu_percents = monitor(target=run_predict)

上述脚本的 cpu_percents 中的值类似于:

关于python - 如何分析 Python 脚本的 CPU 使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197916/

相关文章:

python - 我的 CNN Keras 预测不正确,我不知道该怎么办

使用 JProfiler (7.0.1) 和执行时间审查的 java webapplication 分析

c - 函数的执行时间

python - 使用 Tesseract 识别页面上的单个字符

python - 包含任意用户定义的函数的最佳方式?

python - 类型错误 : Output tensors to a Model must be Keras tensors

scikit-learn - 如何在 Scikit-learn 管道中访问回归器的权重

c++ - 如何在 OSX 中获取程序的最大内存使用量

python - ctypes bigendianstruct Littlendianstruct 对单字节返回不同的结果

python - 需要在 Python(或命令行)中以编程方式转换 PDF 纸张大小(例如 US-Letter 到 A4)