簡體   English   中英

如何在 jupyter notebook 5 中逐行分析 python 3.5 代碼

[英]How to profile python 3.5 code line by line in jupyter notebook 5

如何找出每行python代碼所花費的執行時間。

line_profiler 適用於 ipython,但不適用於 jupyter notebook。 我嘗試將@profile 添加到我的函數中,它給出了錯誤,提示未定義名稱“profile”。 有一種方法可以通過 time.time() 做到這一點,但我想知道是否有任何內置的分析功能可以分析我函數的每一行並顯示執行時間。

def prof_function():
    x=10*20
    y=10+x
    return (y)

您可以在 jupyter 筆記本中使用line_profiler

  1. 安裝它: pip install line_profiler
  2. 在您的 jupyter notebook 中,調用: %load_ext line_profiler
  3. 像示例中一樣定義函數prof_function
  4. 最后,配置如下: %lprun -f prof_function prof_function()

這將提供輸出:

Timer unit: 1e-06 s

Total time: 3e-06 s
File: <ipython-input-22-41854af628da>
Function: prof_function at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def prof_function():
     2         1          1.0      1.0     33.3      x=10*20
     3         1          1.0      1.0     33.3      y=10+x
     4         1          1.0      1.0     33.3      return (y)

為了獲得每一行的執行時間並獲得漂亮的彩色編碼熱圖,我使用了這個漂亮的 ipython 魔法...... https://github.com/csurfer/pyheatmagic

在此處輸入圖片說明

安裝:

pip 安裝 py-heat-magic

要分析筆記本中的每一行:

  • 復制你的筆記本。
  • 合並所有單元格(突出顯示所有和 shift-m)
  • 在頂部創建一個新單元格
  • 進入

%load_ext heat

在第二個單元格的頂部,在第一行輸入:

%%heat  

如果您的代碼超過 2000 行,您可能會遇到問題。

只是@SA 答案的摘要

!pip install line_profiler
%load_ext line_profiler

def func():
    print('hi')

%lprun -f func func()

安裝線分析器

conda install line_profiler

有關http://mortada.net/easily-profile-python-code-in-jupyter.html 的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM