Python性能分析

Python性能分析

http://www.javashuo.com/article/p-cmjhwjeg-ea.html
https://www.cnblogs.com/cbscan/articles/3341231.htmlhtml

使用ipdbpython

使用profileweb

import profile  
def profileTest():  
   Total =1;  
   for i in range(10):  
       Total=Total*(i+1)  
       print Total  
   return Total  
if __name__ == "__main__":  
   profile.run("profileTest()")

cProfile性能優化

python -m cProfile -s cumulative -o profile.stats test_time.py

Profile的成員函數:
enable(): 開始收集性能分析數據
disable(): 中止收集性能分析數據
create_stats(): 中止收集分析數據,併爲已收集的數據建立stats對象
print_stats(): 建立stats對象並打印分析結果
dump_stats(filename): 把當前性能分析的結果寫入文件(二進制格式)
runcall(func, *args, **kwargs): 收集被調用函數func的性能分析數據Stats類
pstats模塊提供的Stats類能夠幫助咱們讀取和操做stats文件(二進制格式)ide

cProfile

在python代碼中調用cProfile函數

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

輸出爲:工具

197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 re.py:212(compile)
     1    0.000    0.000    0.001    0.001 re.py:268(_compile)
     1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
     1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
     4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
   3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

從分析報告結果中咱們能夠獲得不少信息:性能

  • 整個過程一共有197個函數調用被監控,其中192個是原生調用(即不涉及遞歸調用)
  • 總共執行的時間爲0.002秒
  • 結果列表中是按照標準名稱進行排序,也就是按照字符串的打印方式(數字也看成字符串)
    在列表中:
  • ncalls表示函數調用的次數(有兩個數值表示有遞歸調用,總調用次數/原生調用次數)
  • tottime是函數內部調用時間(不包括他本身調用的其餘函數的時間)
  • percall等於 tottime/ncalls
  • cumtime累積調用時間,與tottime相反,它包含了本身內部調用函數的時間
  • 最後一列,文件名,行號,函數名

參考資料

http://python.jobbole.com/87621/優化

Python性能優化

pypy,numba,cython
ctypes,swig
cfficode

參考資料

http://pypy.org/
ctypes官方文檔:https://docs.python.org/3/library/ctypes.html

相關文章
相關標籤/搜索