【问题标题】:How to profile python 3.5 code line by line in jupyter notebook 5如何在 jupyter notebook 5 中逐行分析 python 3.5 代码
【发布时间】:2017-11-27 19:02:03
【问题描述】:

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

line_profiler 适用于 ipython,但不适用于 jupyter notebook。我尝试将@profile 添加到我的函数中,它给出了错误,说名称'profile' 没有定义。 time.time() 有一种方法可以做到这一点,但我想知道是否有任何内置的分析函数可以分析我的函数的每一行并显示执行时间。

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

【问题讨论】:

    标签: python python-3.x profiling jupyter-notebook


    【解决方案1】:

    安装线分析器

    conda install line_profiler

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

    【讨论】:

      【解决方案2】:

      您可以在 jupyter notebook 中使用line_profiler

      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)
      

      【讨论】:

      • 运行时中断执行也能正常工作!
      【解决方案3】:

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

      安装:

      pip install py-heat-magic

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

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

      %load_ext heat

      在第二个单元格的顶部第一行输入:

      %%heat  
      

      如果您的代码行数超过 2000 行,您可能会遇到问题。

      【讨论】:

      【解决方案4】:

      只是@S.A.的回答的摘要

      !pip install line_profiler
      %load_ext line_profiler
      
      def func():
          print('hi')
      
      %lprun -f func func()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-23
        • 2021-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-19
        • 2018-09-15
        相关资源
        最近更新 更多