有几种方法。
import cProfile
import pstats
import sys
def function(n):
a = 1
for i in range(n):
a += 1
return a
第一个是使用一个简单的包装器runctx()
,它允许您为执行的字符串指定全局变量和局部变量。在下面的示例中,我使用globals()
传递function
对象和locals
传递参数,但当然可以不同的排列方式。
def profile1():
cProfile.runctx("function(n)", globals(), dict(n=int(sys.argv[1])), filename='test')
return pstats.Stats('test')
一个不需要弄乱的更好方法exec
是使用Profile
类。这样你就可以分析一段常规代码:
def profile2():
pr = cProfile.Profile()
pr.enable()
function(int(sys.argv[1]))
pr.disable()
return pstats.Stats(pr)
只是为了完整起见,使示例可运行
if __name__ == '__main__':
profile1().print_stats()
profile2().print_stats()