2012-07-06 32 views
3

在我写的Python代码在同一个文件中的所有功能,过去,我可以使用下面的代码分析我的计划:我怎样才能剖析我的python应用程序的类方法?

这是一个装饰我写道:

def do_profile(cond): 
    def resdec(f): 
     if not cond: 
      return f 
     return profile(f) 
    return resdec 

这是我如何使用它:

@do_profile(DO_PROFILE) 
def my_func(): 
    return 1 

话,我会调用我的脚本kernprof.py

kernprof.py -l my_program.py 

同时我更熟悉OOP和我重写我的程序分成许多类和程序现在开始是这样的:

if __name__ == "__main__": 
    my_app = myApp() 
    my_app.run() 

myApp是一类还大量与其他类通信:

class myApp(): 
    @do_profile(DO_PROFILE) 
    def foo_method(self, arg1): 
     pass 

我已经添加在每个myApp方法的前面的装饰do_profile,但如果我运行kernprof.py,所得.prof文件是空

那么分析一个类的方法最简单的方法是什么?我真的很喜欢用装饰者和旗帜来开关这个开关。

EDIT1:我对这里最简单的解决方案非常感兴趣。找一个装饰者成为一个优雅的解决方案,但也许事情可以做得更容易。我不想做的是使用像cProfile's配置文件profile.runctx('self.baz()', globals(), locals())。处理很多类和方法时,这不是一个实际的解决方案。

回答

1

profile功能是装饰自己,而最喜欢的装饰,它们需要被应用到的功能只。

幸运的是,类方法基本上是在创建实例时绑定到实例的函数。因此,你可以把它在类定义由方法本身适用于你的装饰于任何类方法:

class myApp(object): 
    @do_profile(DO_PROFILE) 
    def foo_method(self, arg1): 
     pass 

    @do_profile(DO_PROFILE) 
    def bar_method(self, arg2): 
     pass 

如果您使用Python 2.6或者,你也可以创建一个class decorator和应用profile装饰器全部方法在任何给定的类。

@do_profile_all_methods(DO_PROFILE) 
class myApp(object): 
    def foo_method(self): 
     pass 

这样的装饰可能是这个样子:

import types 

def do_profile_all_methods(cond): 
    if not cond: 
     return lambda c: C# Do nothing with the class; the 'null' decorator 
    def profile_all_methods(klass): 
     for name, attr in klass.__dict__.items(): 
      if isinstance(attr, types.UnboundMethodType): 
       klass[name] = profile(attr) 
     return klass 
    return profile_all_methods 

这个装饰仅适用的profile包装直接的方法,而不是你想通过将装饰类定义之前正确应用它任何从基类继承而来的。

+0

你如何使用它?你能给出完整的工作例子吗? – 2017-11-17 01:43:13

+0

@johnktejik:答案已包括工作示例。 – 2017-11-17 08:30:04

+0

不,我得到一个错误,说DO_PROFILE没有定义。 – 2017-11-18 19:04:48

2

看看Yappi

要分析的一段代码简单地使用:

import yappi 
[...] 
yapp.start() 
some_function_that_needs_profiling() 
yappi.print_stats() 
+1

所以如果'some_function_that_needs_profiling()'实例化一堆对象,它们各自的方法是否会自动进行配置? – memyself 2012-07-06 09:10:18

+0

on python3.5我得到一个错误 AttributeError:模块'yappi'没有属性'print_stats' – 2017-08-03 11:17:59