繁体   English   中英

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

[英]how profiling class method using IPython %lprun magic function

如何剖析在函数内部调用的对象的方法? 我在jupyter笔记本中使用%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参数中填充类方法才能起作用?

根据文档 ,“ cProfile仅对显式函数调用进行排序,而不是由于语法而对特殊方法进行调用”,因此它应该可以工作。

我发现的一个(也许)相关问题在这里

TL; DR:在%lprun -f foo.compute my_func()使用foo而不是在您的示例中使用my_foo


给定当前示例,您可以按如下方式配置您的类和方法:

  1. %load_ext line_profiler

  2. %lprun -f my_func my_func()调用类的函数: %lprun -f my_func my_func() ,该%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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM