Python番外(3)——P72性能分析

首先將下列代碼保存到cprof_example.py文件:

import numpy as np
from numpy.linalg import eigvals

'''函數'''
def run_experiment(niter = 100):
    K = 100
    results = []
    for _ in xrange(niter):
        mat = np.random.randn(K,K)
        max_eigenvalue = np.abs(eigvals(mat)).max()
        results.append(max_eigenvalue)
    return results

'''調用'''
some_results = run_experiment()
print 'Largest one we saw:%s' %np.max(some_results)

然後再命令行中,到該目錄下執行:

python -m cProfile -s cumulative cprof_example.py

執行上面代碼,命令行會出現很多行數據,不方便閱讀,可改爲:

python -m cProfile -o log.txt cprof_example.py

這樣,結果會保存在log.txt中,log.txt可以用VPT(http://visualpytune.googlecode.com)打開,要翻牆,這篇博文有翻牆工具:
MLAPP
這裏有更詳細的cProfile的資料:
https://docs.python.org/2/library/profile.html

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