命令列中的行分析器
在我們想要分析的函式之前使用 @profile 指令的原始碼:
import requests
@profile
def slow_func():
s = requests.session()
html=s.get("https://en.wikipedia.org/").text
sum([pow(ord(x),3.1) for x in list(html)])
for i in range(50):
slow_func()
使用 kernprof 命令逐行計算分析
$ kernprof -lv so6.py
Wrote profile results to so6.py.lprof
Timer unit: 4.27654e-07 s
Total time: 22.6427 s
File: so6.py
Function: slow_func at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 @profile
5 def slow_func():
6 50 20729 414.6 0.0 s = requests.session()
7 50 47618627 952372.5 89.9 html=s.get("https://en.wikipedia.org/").text
8 50 5306958 106139.2 10.0 sum([pow(ord(x),3.1) for x in list(html)])
頁面請求幾乎總是比基於頁面資訊的任何計算慢。