問(wèn)題定義
想要優(yōu)化Java中的內(nèi)存管理锉屈,就要查看GC_log來(lái)定位內(nèi)存瓶頸代乃;同理匀泊,想要優(yōu)化python代碼断部,就要統(tǒng)計(jì)各函數(shù)的運(yùn)行時(shí)間來(lái)定位性能瓶頸猎贴。
最方便的就是直接使用jupyter notebook自帶的兩個(gè)magic指令:%prun
和%lprun
注意:本文默認(rèn)讀者已經(jīng)熟悉Jupyter notebook和python基礎(chǔ)。如果您需要復(fù)習(xí),可以參考這篇文章
%prun[1]
用來(lái)統(tǒng)計(jì)各函數(shù)調(diào)用次數(shù)及耗時(shí)她渴。e.g. :
def f():
# additional line1...
# additional line2...
scores = detector.run_cases(cases_ballon, allow_near_phones=False, show_phone_heatmap=False, fig_ratio=(1, 1))
# additional line3...
# -T選項(xiàng)指定寫(xiě)到的文本文件达址, -l選項(xiàng)指定只顯示前多少行
# 另外也可以用 -l <partial func name> 來(lái)過(guò)濾,只保留name包含指定子串的函數(shù)
%prun -T ./res/prun.txt -l 20 f()
# 另外還有一個(gè)cell magic趁耗,叫 %%prun
# 它相當(dāng)于把cell內(nèi)的多行代碼沉唠,合并成一行長(zhǎng)代碼;作為最后一個(gè)參數(shù)送給 %prun苛败;以免用f()來(lái)封裝代碼的麻煩
運(yùn)行上述cell满葛,會(huì)在jupyter notebook中彈窗顯示如下結(jié)果,并寫(xiě)到文本文件./res/prun.txt
982179 function calls (971601 primitive calls) in 2.241 seconds
Ordered by: internal time
List reduced from 1716 to 5 due to restriction <5>
ncalls tottime percall cumtime percall filename:lineno(function)
1390 1.422 0.001 1.551 0.001 ctc_based_kws.py:320(score_by_sliding_window)
436939 0.126 0.000 0.126 0.000 {built-in method builtins.max}
81438 0.020 0.000 0.033 0.000 {built-in method builtins.isinstance}
7639/7480 0.015 0.000 0.017 0.000 {built-in method numpy.core.multiarray.array}
2797 0.014 0.000 0.019 0.000 weakref.py:101(__init__)
如上所示著拭,累計(jì)耗時(shí)最多的function call為score_by_sliding_window()
纱扭,位于ctc_based_kws.py:320
,消耗了1.422秒儡遮;其次是某處對(duì)python/numpy內(nèi)置的max()
的調(diào)用乳蛾。
通過(guò)prun能獲得的信息就是這些,只能精確到函數(shù)級(jí)鄙币,而且對(duì)于內(nèi)置函數(shù)提供的有用信息并不多肃叶。
想要進(jìn)一步定位問(wèn)題,可以對(duì)關(guān)鍵的幾個(gè)函數(shù)實(shí)施代碼行級(jí)別的profiling十嘿,即%lprun
%lprun[2]
lprun跟prun只有一字之差因惭,但是功能不同——是用來(lái)統(tǒng)計(jì)各行代碼的調(diào)用次數(shù)和時(shí)間的。
而且绩衷,前者并沒(méi)有內(nèi)置到python中蹦魔,而且通過(guò)一個(gè)叫作line_profiler
的第三方庫(kù)[3]來(lái)實(shí)現(xiàn)的。
!pip install line_profiler
%load_ext line_profiler # 將這個(gè)模塊加載到ipython kernel中
# 也可以通過(guò)改配置文件的方式咳燕,來(lái)永久地自動(dòng)加載這個(gè)模塊
# vi ~/.ipython/profile_default/ipython_config.py
# c.TerminalIPythonApp.extensions = ['line_profiler',]
# 參考: https://stackoverflow.com/questions/19942653/interactive-python-cannot-get-lprun-to-work-although-line-profiler-is-impor
用起來(lái)也比較直觀勿决,e.g.:
# 沒(méi)有-l選項(xiàng)了,只有-f和-m選項(xiàng)
# -f func1 -f func2 -m module1 -m module2 <code to profile> 表示只統(tǒng)計(jì)指定的func1和func2兩個(gè)函數(shù)招盲,以及module1和module2兩個(gè)模塊的代碼行
# 注意-f指定的必須是可以找到的函數(shù)對(duì)象低缩,不是函數(shù)名稱(chēng)的子串,這一點(diǎn)跟prun有區(qū)別
%lprun -T ./res/lprun.txt -f Detector.score_by_sliding_window f()
結(jié)果
# 注意時(shí)間單位是默認(rèn)的曹货,最新版的line_profile支持-u選項(xiàng)來(lái)設(shè)置咆繁,但是還沒(méi)推到pipy上
Timer unit: 1e-06 s
Total time: 0.000665 s
File: /Users/qianws/anaconda/lib/python3.5/site-packages/numpy/core/fromnumeric.py
Function: amax at line 2174
Line # Hits Time Per Hit % Time Line Contents
==============================================================
2174 def amax(a, axis=None, out=None, keepdims=np._NoValue):
2175 """
2257 ... docstring ...
2258 """
2259 100 66 0.7 9.9 kwargs = {}
2260 100 62 0.6 9.3 if keepdims is not np._NoValue:
2261 kwargs['keepdims'] = keepdims
2262
2263 100 72 0.7 10.8 if type(a) is not mu.ndarray:
2264 try:
2265 amax = a.max
2266 except AttributeError:
2267 pass
2268 else:
2269 return amax(axis=axis, out=out, **kwargs)
2270
2271 100 74 0.7 11.1 return _methods._amax(a, axis=axis,
2272 100 391 3.9 58.8 out=out, **kwargs)
Total time: 5.67407 s # 逐行統(tǒng)計(jì)時(shí)間本身也對(duì)耗時(shí)也干擾,這里的數(shù)字比正常運(yùn)行時(shí)偏大
File: /Users/qianws/jupyterNotebooks/KWS/ctc_based_kws.py
Function: score_by_sliding_window at line 320
Line # Hits Time Per Hit % Time Line Contents
==============================================================
320 def score_by_sliding_window(self, l: List[str], P: np.ndarray) -> float:
321 """... docstring ..."""
...
335 55600 44393 0.8 0.8 for t in range(1, T):
336 542100 469812 0.9 8.3 for s in range(0, S):
...
349 487890 494446 1.0 8.7 if s >= 2 and l[s] != l[s - 2] and l[s] != '_':
350 162630 499166 3.1 8.8 a[s, t] = walk_fn([a[s, t - 1] * mut_l, a[s - 1, t - 1] * p, a[s - 2, t - 1] * p])
351 325260 255332 0.8 4.5 elif s >= 1:
352 271050 721568 2.7 12.7 a[s, t] = walk_fn([a[s, t - 1] * mut_l, a[s - 1, t - 1] * p])
353 else:
354 54210 79284 1.5 1.4 a[s, t] = mut_l * (a[s, t - 1]) # l[0]必然是blank顶籽,其概率不參與重復(fù)的連乘
...
361 1390 1314 0.9 0.0 return res
不難看出玩般,第352行的walk_fn的調(diào)用占了12.7%的時(shí)間,是重點(diǎn)優(yōu)點(diǎn)目標(biāo)礼饱。
至于其內(nèi)部具體哪一行慢壤短,可以如法炮制设拟,再跑一輪%lprun
-
API詳見(jiàn) http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-prun ?
-
沒(méi)有獨(dú)立的API文檔頁(yè),只能看docstring久脯,詳見(jiàn) https://github.com/rkern/line_profiler/blob/master/line_profiler.py 第266行 ?
-
項(xiàng)目地址 https://github.com/rkern/line_profiler ?