Python實(shí)現(xiàn)監(jiān)控內(nèi)存使用情況和代碼執(zhí)行時(shí)間
我的代碼的哪些部分運(yùn)行時(shí)間最長(zhǎng)、內(nèi)存最多?我怎樣才能找到需要改進(jìn)的地方?”
在開(kāi)發(fā)過(guò)程中,我很確定我們大多數(shù)人都會(huì)想知道這一點(diǎn),而且通常情況下存在開(kāi)發(fā)空間。在本文中總結(jié)了一些方法來(lái)監(jiān)控 Python 代碼的時(shí)間和內(nèi)存使用情況。
本文將介紹4種方法,前3種方法提供時(shí)間信息,第4個(gè)方法可以獲得內(nèi)存使用情況。
- time 模塊
- %%time 魔法命令
- line_profiler
- memory_profiler
time 模塊
這是計(jì)算代碼運(yùn)行所需時(shí)間的最簡(jiǎn)單、最直接(但需要手動(dòng)開(kāi)發(fā))的方法。他的邏輯也很簡(jiǎn)單:記錄代碼運(yùn)行之前和之后的時(shí)間,計(jì)算時(shí)間之間的差異。這可以實(shí)現(xiàn)如下:
importtime start_time=time.time() result=5+2 end_time=time.time() print('Time taken = {} sec'.format(end_time-start_time))
下面的例子顯示了for循環(huán)和列表推導(dǎo)式在時(shí)間上的差異:
importtime # for loop vs. list comp list_comp_start_time=time.time() result= [iforiinrange(0,1000000)] list_comp_end_time=time.time() print('Time taken for list comp = {} sec'.format(list_comp_end_time-list_comp_start_time)) result=[] for_loop_start_time=time.time() foriinrange(0,1000000): result.append(i) for_loop_end_time=time.time() print('Time taken for for-loop = {} sec'.format(for_loop_end_time-for_loop_start_time)) list_comp_time=list_comp_end_time-list_comp_start_time for_loop_time=for_loop_end_time-for_loop_start_time print('Difference = {} %'.format((for_loop_time-list_comp_time)/list_comp_time*100))
我們都知道for會(huì)慢一些
Time taken for list comp = 0.05843973159790039 sec Time taken for for-loop = 0.06774497032165527 sec Difference = 15.922795107582594 %
%%time 魔法命令
魔法命令是IPython內(nèi)核中內(nèi)置的方便命令,可以方便地執(zhí)行特定的任務(wù)。一般情況下都實(shí)在jupyter notebook種使用。
在單元格的開(kāi)頭添加%%time ,單元格執(zhí)行完成后,會(huì)輸出單元格執(zhí)行所花費(fèi)的時(shí)間。
%%time defconvert_cms(cm, unit='m'): ''' Function to convert cm to m or feet ''' ifunit=='m': returncm/100 returncm/30.48 convert_cms(1000)
結(jié)果如下:
CPU times: user 24 µs, sys: 1 µs, total: 25 µs
Wall time: 28.1 µs
Out[8]: 10.0
這里的CPU times是CPU處理代碼所花費(fèi)的實(shí)際時(shí)間,Wall time是事件經(jīng)過(guò)的真實(shí)時(shí)間,在方法入口和方法出口之間的時(shí)間。
line_profiler
前兩個(gè)方法只提供執(zhí)行該方法所需的總時(shí)間。通過(guò)時(shí)間分析器我們可以獲得函數(shù)中每一個(gè)代碼的運(yùn)行時(shí)間。
這里我們需要使用line_profiler包。使用pip install line_profiler。
importline_profiler defconvert_cms(cm, unit='m'): ''' Function to convert cm to m or feet ''' ifunit=='m': returncm/100 returncm/30.48 # Load the profiler %load_extline_profiler # Use the profiler's magic to call the method %lprun-fconvert_cmsconvert_cms(1000, 'f')
輸出結(jié)果如下:
Timer unit: 1e-06 s
Total time: 4e-06 s
File: /var/folders/y_/ff7_m0c146ddrr_mctd4vpkh0000gn/T/ipykernel_22452/382784489.py
Function: convert_cms at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def convert_cms(cm, unit='m'):
2 '''
3 Function to convert cm to m or feet
4 '''
5 1 2.0 2.0 50.0 if unit == 'm':
6 return cm/100
7 1 2.0 2.0 50.0 return cm/30.48
可以看到line_profiler提供了每行代碼所花費(fèi)時(shí)間的詳細(xì)信息。
- Line Contents :運(yùn)行的代碼
- Hits:行被執(zhí)行的次數(shù)
- Time:所花費(fèi)的總時(shí)間(即命中次數(shù)x每次命中次數(shù))
- Per Hit:一次執(zhí)行花費(fèi)的時(shí)間,也就是說(shuō) Time = Hits X Per Hit
- % Time:占總時(shí)間的比例
可以看到,每一行代碼都詳細(xì)的分析了時(shí)間,這對(duì)于我們分析時(shí)間相當(dāng)?shù)挠袔椭?/p>
memory_profiler
與line_profiler類似,memory_profiler提供代碼的逐行內(nèi)存使用情況。
要安裝它需要使用pip install memory_profiler。我們這里監(jiān)視convert_cms_f函數(shù)的內(nèi)存使用情況
from conversions import convert_cms_f import memory_profiler %load_ext memory_profiler %mprun -f convert_cms_f convert_cms_f(1000, 'f')
convert_cms_f函數(shù)在單獨(dú)的文件中定義,然后導(dǎo)入。結(jié)果如下:
Line # Mem usage Increment Occurrences Line Contents
=============================================================
1 63.7 MiB 63.7 MiB 1 def convert_cms_f(cm, unit='m'):
2 '''
3 Function to convert cm to m or feet
4 '''
5 63.7 MiB 0.0 MiB 1 if unit == 'm':
6 return cm/100
7 63.7 MiB 0.0 MiB 1 return cm/30.48
memory_profiler 提供對(duì)每行代碼內(nèi)存使用情況的詳細(xì)了解。
這里的1 MiB (MebiByte) 幾乎等于 1MB。1 MiB = 1.048576 1MB
但是memory_profiler 也有一些缺點(diǎn):它通過(guò)查詢操作系統(tǒng)內(nèi)存,所以結(jié)果可能與 python 解釋器略有不同,如果在會(huì)話中多次運(yùn)行 %mprun,可能會(huì)注意到增量列報(bào)告所有代碼行為 0.0 MiB。這是因?yàn)槟Х畹南拗茖?dǎo)致的。
雖然memory_profiler有一些問(wèn)題,但是它就使我們能夠清楚地了解內(nèi)存使用情況,對(duì)于開(kāi)發(fā)來(lái)說(shuō)是一個(gè)非常好用的工具
總結(jié)
雖然Python并不是一個(gè)以執(zhí)行效率見(jiàn)長(zhǎng)的語(yǔ)言,但是在某些特殊情況下這些命令對(duì)我們還是非常有幫助的。
以上就是Python實(shí)現(xiàn)監(jiān)控內(nèi)存使用情況和代碼執(zhí)行時(shí)間的詳細(xì)內(nèi)容,更多關(guān)于Python監(jiān)控內(nèi)存的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)調(diào)度算法代碼詳解
這篇文章主要介紹了Python實(shí)現(xiàn)調(diào)度場(chǎng)算法代碼詳解,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12Python實(shí)現(xiàn)的一個(gè)自動(dòng)售飲料程序代碼分享
這篇文章主要介紹了Python實(shí)現(xiàn)的一個(gè)自動(dòng)售飲料程序代碼分享,就是用python實(shí)現(xiàn)的生活中一種投幣式自動(dòng)售飲料機(jī)的內(nèi)部程序判斷代碼,需要的朋友可以參考下2014-08-08python讀取并繪制nc數(shù)據(jù)的保姆級(jí)教程
其實(shí)目前很多數(shù)據(jù)以nc格式存儲(chǔ),這篇文章主要給大家介紹了關(guān)于python讀取并繪制nc數(shù)據(jù)的保姆級(jí)教程,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05Python源碼學(xué)習(xí)之PyType_Type和PyBaseObject_Type詳解
今天給大家?guī)?lái)的是關(guān)于Python源碼的相關(guān)知識(shí)學(xué)習(xí),文章圍繞著PyType_Type和PyBaseObject_Type展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06