首页 > 解决方案 > 我将如何计算这个 python 程序的运行时间、内存和 CPU 使用率?

问题描述

有人可以详细解释一下如何计算这个使用 ARIMA 模型进行预测的 Python 程序的运行时间、CPU 使用率和内存使用率:

def ARIMA_forecast(series, df):
    X = series.values
    size = int(len(X) * 0.66)
    train, test = X[0:size], X[size:len(X)]
    history = [x for x in train]
    predictions = list()
    start_time = time.process_time()
    for t in range(len(test)):
        model = ARIMA(history, order=(4, 1, 0))
        model_fit = model.fit(disp=0)
        output = model_fit.forecast()
        yhat = output[0]
        predictions.append(yhat)
        obs = test[t]
        history.append(obs)
        print('predicted=%f, expected=%f' % (yhat, obs))
    # evaluate forecasts
    end_time = time.process_time()
    print(end_time - start_time)
    rmse = sqrt(mean_squared_error(test, predictions))
    print('Test RMSE: %.3f' % rmse)
    # plot forecasts against actual outcomes
    plt.plot(series, label='Training data')
    plt.plot(series[size:len(X)].index, predictions, color='blue', label='Predicted Price')
    plt.plot(series[size:len(X)].index, test, color='red', label='Actual Price')
    plt.legend()
    plt.show()


df = pd.read_csv('MSFT.csv', header=0, index_col=0, parse_dates=True)
series = df['Adj Close']

ARIMA_forecast(series, df)

现在我正在使用 time.pricess_time() 来测量运行时间。我不确定如何计算 CPU 和内存使用量。我已经阅读了有关使用 psutil 的信息,但我不知道该怎么做。

标签: pythonperformancememorycpu-usagearima

解决方案


对于内存分析,我使用了 pymlerGuppy,它们运行良好。对于 CPU 分析,您的代码似乎是 cpu 密集型的,因此 cpu 时间与执行时间相同。除此之外,我还开发了perf_tools,除了可以使用 time.*_time() 进行分析之外,它还可以向您显示代码每个部分所消耗的时间。例如,函数中的循环可能很难很好地分析,您可以分析精确的 cpu 密集型与绘图侧。


推荐阅读