python - 使用 cProfile 在 Python 中分析类的方法?

标签 python profiler cprofile

我想使用 cProfile 在 Python 中分析函数的方法。我尝试了以下方法:

import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")

但它不起作用。如何使用“run”调用 self.method?

最佳答案

编辑:抱歉,没有意识到配置文件调用是类方法中。

run 只是尝试 exec 你传递给它的字符串。如果 self 未绑定(bind)到您正在使用的分析器范围内的任何内容,则不能在 run 中使用它!使用 runctx将调用范围内的局部和全局变量传递给探查器的方法:

>>> import time
>>> import cProfile as profile
>>> class Foo(object):
...     def bar(self):
...             profile.runctx('self.baz()', globals(), locals())
...
...     def baz(self):
...             time.sleep(1)
...             print 'slept'
...             time.sleep(2)
...
>>> foo = Foo()
>>> foo.bar()
slept
         5 function calls in 2.999 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.999    2.999 <stdin>:5(baz)
        1    0.000    0.000    2.999    2.999 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    2.999    1.499    2.999    1.499 {time.sleep}

注意最后一行:time.sleep 是什么占用了时间。

关于python - 使用 cProfile 在 Python 中分析类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4492535/

相关文章:

javascript - 我如何分析线程化的 javascript?

python - Django + PostgreSQL - 1000 次插入/秒,如何加速?

java - Profiler 选项卡未出现在 visualvm 中以进行远程 jmx 连接

python - python 中的正则表达式 - 找不到特定的字符串

python - 每个 arg 具有多个值的 arg 解析器的最佳实践

python - 如何一次将 3 个键绑定(bind)到一个事件?

multithreading - 50 个线程限制后的 NetBeans 探查器 "stops working"?

python - 如何使用 pypy 进行分析(cProfile 不起作用)

python - cProfile 在调用 numba jit 函数时会增加大量开销

python - Sed 一个衬里在 python 子进程中不起作用