![](/img/trans.png)
[英]Error when profiling an otherwise perfectly working multiprocessing python script with cProfile
[英]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 裝飾器
如果配置文件下的函數返回值,則需要稍微更改@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.