繁体   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