【总结】
优化python程序的流程(自顶向下):
1.先用cProfile找出最耗时的函数,
2.然后在这个函数前面加@profile 用line_profiler(+kernprof)找出最耗时的行,
3.最后用timeit测试下这个行的运行效率。
下面是具体介绍各个部分:
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
0.总体介绍
http://leok.me/2013/06/10/how-to-profile-you-python-code.html
1.cProfile(和Profile)
http://blog.csdn.net/gzlaiyonghao/article/details/2239445
介绍:
http://blog.csdn.net/gzlaiyonghao/article/details/1483728
实践:
http://blog.csdn.net/gzlaiyonghao/article/details/1502290
简而言之:
import cProfile,pstats
cProfile.run("main()","G:\\astar_prof1.txt")
p = pstats.Stats("G:\\astar_prof1.txt")
p.strip_dirs().sort_stats("time").print_stats(10)
2. to calltree(暂时忽略)
pt = pyprof2calltree.CalltreeConverter("G:\\restats")
f = open("G:\\1.txt","w")
pt.output(f)
f.close()
3.line_profiler
介绍:
http://silas.sewell.org/blog/2009/05/28/python-line-by-line-profiler-line_profiler-and-kernprof/
kernprof.py 地址
http://pythonhosted.org/line_profiler/kernprof.py
注意:
在要测试的函数前加@profile(至于为什么还没研究)
然后调用这个函数:
例如:
测试的文件中:
@profile
def main():
pass
main()
命令行(重定向到result.txt):
kernprof.py -l test.py
python -m line_profiler test.py.lprof >> result.txt
4.小巧的 itmeit
http://blog.sina.com.cn/s/blog_6163bdeb0101806e.html
import timeit
t = timeit.Timer("math.sqrt(0.99)","import math")
print t.timeit(10000)
print t.repeat(3,10000)
Timer的第一个参数是要执行的语句或者函数,第二个是“环境”