python 優化

【總結】

優化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的第一個參數是要執行的語句或者函數,第二個是“環境”

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章