如何在Jupyter Notebook 5中逐行描述python 3.5代码

Ase*_*eem 5 python profiling python-3.x jupyter-notebook

如何找出每行python代码花费的执行时间。

line_profiler可用于ipython,但不适用于jupyter笔记本。我尝试将@profile添加到我的函数中,它给出错误消息,提示未定义名称'profile'。有一种方法可以通过time.time()来完成,但是我想知道是否有任何内置的性能分析函数可以对函数的每一行进行配置并显示执行时间。

def prof_function():
    x=10*20
    y=10+x
    return (y)
Run Code Online (Sandbox Code Playgroud)

S.A*_*.A. 30

您可以line_profiler在 jupyter 笔记本中使用。

  1. 安装它: pip install line_profiler
  2. 在您的 jupyter 笔记本中,调用: %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)
Run Code Online (Sandbox Code Playgroud)

  • @托马斯G。我遵循了完全相同的步骤,但它表明要求已经满足,即已经安装。但没有显示行内容“您确定正在从运行探查器的同一目录运行此程序吗?” 继续,不包含函数的内容。可能是什么原因? (2认同)

Tho*_* G. 15

只是@SA 回答的摘要

!pip install line_profiler
%load_ext line_profiler

def func():
    print('hi')

%lprun -f func func()
Run Code Online (Sandbox Code Playgroud)


Dou*_*ugR 6

为了获得每行的执行时间并获得漂亮的彩色编码热图,我使用了这个漂亮的ipython魔术。... https://github.com/csurfer/pyheatmagic

在此处输入图片说明

安装:

点安装py-heat-magic

要分析笔记本中的每一行:

  • 复制您的笔记本。
  • 合并所有单元格(突出显示所有和shift-m)
  • 在顶部创建一个新单元格
  • 输入

%load_ext heat

在第二个单元格的顶部的第一行中输入以下内容:

%%heat  
Run Code Online (Sandbox Code Playgroud)

如果您有2000行以上的代码,则可能会遇到问题。

  • 看起来不错,但请注意以下问题:https://github.com/csurfer/pyheatmagic/issues/6 (2认同)