基于指定函数或指定文件侵入式分析
cProfile:基于lsprof的用C语言实现的扩展应用,运行开销比较合理,适合分析运行时间较长的程序,推荐使用这个模块;
使用cProfile进行性能分析,你可以在Python脚本中实现,也可以使用命令行执行:
if __name__ == "__main__":
import cProfile
# 直接把分析结果打印到控制台
cProfile.run("test()")
# 把分析结果保存到文件中
cProfile.run("test()", filename="result.out")
# 增加排序方式
cProfile.run("test()", filename="result.out", sort="cumulative")
使用命令行运行的方法基本一致,Bash代码如下:
# 直接把分析结果打印到控制台
python -m cProfile test.py
# 把分析结果保存到文件中
python -m cProfile -o result.out test.py
# 增加排序方式
python -m cProfile -o result.out -s cumulative test.py
也可直接对代码段进行分析:
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
#需要调试的代码段
pr.disable()
s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats()
print s.getvalue()
#或
from cProfile import Profile
def runRe():
import re
re.compile("aaa|bbb")
prof = Profile()
prof.enable()
runRe()
prof.create_stats()
prof.print_stats()
- 阅读剩余部分 -