我想從對象的角度來剖析python代碼。例如:Python剖析方法
foo = Foo()
profiled_foo = add_profiling(foo)
# use profiled_foo like foo
...
# later
profiled_foo.print_profile()
我想要調用每個方法的每個方法和累積的時間。我沒有發現類似的東西,儘管我認爲寫作不應該太難。
是否有像這樣的庫存在?或者可能不是因爲通過這種方式分析會是一個壞主意?
基於保麥圭爾的回答是:
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()
。
*** 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)
...
尼斯鏈接。謝謝。 –