如何使用cProfile对Python类的方法进行性能分析?

50 投票
5 回答
41806 浏览
提问于 2025-04-16 08:48

我想用 cProfile 来分析 Python 中一个函数的方法。我试了下面的代码:

import cProfile as profile

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

但是它没有成功。我该怎么用 "run" 来调用 self.method 呢?

5 个回答

5
  import cProfile
  p = cProfile.Profile()
  p.runcall(self.myMethod)
  p.print_stats()

Profile类的详细信息可以在这里找到。

74

编辑:抱歉,我没注意到这个 profile 调用是在一个类的方法里面。

run 只是尝试执行你传给它的字符串。如果在你使用的性能分析器的范围内,self 没有绑定到任何东西,你就不能在 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 是占用时间的原因。

32

使用 profilehooks 装饰器

http://pypi.python.org/pypi/profilehooks

撰写回答