Python分析方法

tau*_*ran 3 python profiling

我想从对象的角度来描述python代码.例如:

foo = Foo()
profiled_foo = add_profiling(foo)

# use profiled_foo like foo
...

# later
profiled_foo.print_profile()
Run Code Online (Sandbox Code Playgroud)

我希望按方法调用每个方法花费的累计时间.我没有发现任何类似的东西,虽然我认为写起来不应该太难.

这样的图书馆存在吗?或者也许不是因为这种方式分析会是一个坏主意?


根据Paul McGuire的回答:

import inspect

from time import sleep
from profilehooks import profile

class Foo(object):
    def a(self):
        sleep(0.1)

    def b(self):
        sleep(0.3)

    def c(self):
        sleep(0.5)

def add_profiling(obj):
    for k in dir(obj):
        attr = getattr(obj, k)
        if inspect.ismethod(attr) and k != '__init__':
            setattr(obj, k, profile(attr))

if __name__ == '__main__':
    foo = Foo()
    add_profiling(foo)

    foo.a()
    foo.a()
    foo.b()
    foo.b()
    foo.a()
    foo.c()
Run Code Online (Sandbox Code Playgroud)

.

*** PROFILER RESULTS ***
c (oprof.py:13)
function called 1 times

         3 function calls in 0.501 CPU seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.501    0.501 oprof.py:13(c)
        1    0.501    0.501    0.501    0.501 {time.sleep}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)

...
Run Code Online (Sandbox Code Playgroud)

Pau*_*McG 6

我在这些装饰器上取得了相当不错的成功:http://mg.pov.lt/profilehooks/