python - 如何使用 IPython %lprun 魔术函数分析类方法

标签 python class ipython profiling jupyter-notebook

如何分析在函数内部调用的对象的方法?我在 jupyter notebook 中使用 %lprun 魔法。请参阅以下 ex.py 示例文件:

class foo():
    def __init__(self, a=0, n=1):
                self.a=a
                self.n=n

    def compute(self):
        result = 0
        for i in range(self.n):
            result += self.a
        return result 

def my_func():
    a = 1
    n = 1000
    my_foo = foo(a, n)
    result = my_foo.compute()
    print(result)

然后,从我的 jupyter 笔记本,我可以分析 my_func:

 from ex import my_func

 %lprun -f my_func my_func()

但我无法分析我的compute 方法:

from ex import my_func

%lprun -f my_foo.compute my_func()

我想要的有可能吗?我必须如何在 -f 参数中填充类方法才能使其工作?

根据documentation ,“cProfile 只计算显式函数调用,而不是因为语法调用的特殊方法”,...所以它应该可以工作。

我发现的一个(可能)相关问题is here .

最佳答案

TL;DR:在 %lprun -f foo.compute my_func() 中使用 foo my_foo 如您的示例所示。


鉴于当前示例,您可以这样分析您的类和方法:

  1. %load_ext line_profiler

  2. 分析调用类的函数:%lprun -f my_func my_func(),返回:


Timer unit: 1e-06 s

Total time: 0.000363 s
File: <ipython-input-111-dedac733c95b>
Function: my_func at line 12

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    12                                           def my_func():
    13         1          2.0      2.0      0.6      a = 1
    14         1          1.0      1.0      0.3      n = 1000
    15         1          4.0      4.0      1.1      my_foo = foo(a, n)
    16         1        278.0    278.0     76.6      result = my_foo.compute()
    17         1         78.0     78.0     21.5      print(result)

  1. 然后,经过检查,您会发现大部分时间都花在了您的方法 my_foo.compute() 上。 my_foofoo 类的一个实例,因此您可以进行更具体的分析器调用 %lprun -f foo.compute my_func(),返回:

Timer unit: 1e-06 s

Total time: 0.001566 s
File: <ipython-input-12-e96be9cf3108>
Function: compute at line 6

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     6                                               def compute(self):
     7         1          3.0      3.0      0.2          result = 0
     8      1001        765.0      0.8     48.9          for i in range(self.n):
     9      1000        797.0      0.8     50.9              result += self.a
    10         1          1.0      1.0      0.1          return result

关于python - 如何使用 IPython %lprun 魔术函数分析类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49136737/

相关文章:

python - 我们需要在 python 中使用 open 关闭文件吗?

java - fragment 内的非法封闭实例

python - 对象不匹配

ipython - 更改 IPython (Jupyter) 中 Latex 输出的颜色

python - 如何在 Pandas 中绘制非内联图像

python - 将字典的长度修改为确定的值并保留具有最高值的键

python - 从 pandas DataFrame 中提取符合条件的单元格索引

python - 关于 pymatbridge

c++ - 无法在没有初始化的情况下声明类?

python - 在 ZSh 中找不到 Anaconda?