Python 分析方法

标签 python profiling

我想从对象的角度分析 python 代码。例如:

foo = Foo()
profiled_foo = add_profiling(foo)

# use profiled_foo like foo
...

# later
profiled_foo.print_profile()

而且我想获得每个方法的调用次数和每个方法花费的累计时间。我没有找到类似的东西,虽然我认为写起来应该不会太难。

有这样的图书馆吗?或许不是因为以这种方式分析不是一个好主意?


基于 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()

.

*** 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)

...

最佳答案

我使用这些装饰器取得了相当大的成功:http://mg.pov.lt/profilehooks/

关于Python 分析方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7892469/

相关文章:

python - 任务队列停止工作

python - Selenium XPath 找到 gif 点击

profiling - 周期计数测量

haskell - 在GHC中自动分配成本中心

ios - iOS 中的内存泄漏,AVPlayer 永远不会被释放

python - 将索引值设置为 date.time pandas 时遇到问题

python - Pandas 时间序列用周末均值生成的一个值替换周末

python - 导入错误:没有名为 'nose' 的模块

启用分析的 Haskell 重新安装基础

c++ - Profiler 显示没有时间进行跳跃,但有很多时间进行比较