簡體   English   中英

使用 cProfile 在 Python 中分析類的方法?

[英]profiling a method of a class in Python using cProfile?

我想使用 cProfile 在 Python 中分析一個函數的方法。 我嘗試了以下方法:

import cProfile as profile

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

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

編輯:抱歉,沒有意識到配置文件調用是類方法中。

run只是嘗試exec您傳遞給它的字符串。 如果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是占用時間的內容。

使用 profilehooks 裝飾器

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

如果配置文件下的函數返回值,則需要稍微更改@katrielalex 的優秀答案:

...             profile.runctx('val = self.baz()', globals(), locals())
...             print locals()['val']

我不建議分析單個例程,因為這意味着提前知道那里存在問題。

性能問題的一個基本方面是它們是偷偷摸摸的。 它們不在您認為的位置,因為如果是,您早就解決了。

最好以實際工作負載運行整個程序,讓分析技術告訴您問題出在哪里。

下面是一個分析發現問題的例子,它不是預期的。

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

Profile類記錄 在此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM