首頁  >  文章  >  後端開發  >  python函數運行記憶體時間等效能檢測工具怎麼用

python函數運行記憶體時間等效能檢測工具怎麼用

WBOY
WBOY轉載
2023-05-10 12:40:13920瀏覽

基礎測試函數

首先,來寫一個基礎的python函數用於在後面的各種效能測試。

def base_func():
    for n in range(10000):
        print('当前n的值是:{}'.format(n))

memory_profiler進程

memory_profiler是python的非標準函式庫,所以這裡採用pip的方式來安裝。它能夠監視進程、了解記憶體使用等情況。

pip install memory_profiler

安裝好memory_profiler函式庫以後,直接使用註解的方式來測試。

from memory_profiler import profile
@profile
def base_func1():
    for n in range(10000):
        print('当前n的值是:{}'.format(n))
base_func1()
# Line #    Mem usage    Increment  Occurrences   Line Contents
# =============================================================
#     28     45.3 MiB     45.3 MiB           1   @profile
#     29                                         def base_func():
#     30     45.3 MiB      0.0 MiB       10001       for n in range(10000):
#     31     45.3 MiB      0.0 MiB       10000           print('当前n的值是:{}'.format(n))

從傳回的資料結果來看,執行目前函數使用了45.3 MiB的記憶體。

timeit 時間使用情況

timeit是python的內建模組,可以測試單元格的程式碼運行時間,由於是內建模組所以並不需要單獨安裝。

import timeit
def base_func2():
    for n in range(10000):
        print('当前n的值是:{}'.format(n))
res = timeit.timeit(base_func2,number=5)
print('当前的函数的运行时间是:{}'.format(res))
# 当前的函数的运行时间是:0.9675800999999993

根據上面函數的運行返回結果,函數的運行時間是0.96秒。

line_profiler行程式碼偵測

如果在只需要偵測函數的局部運行時間的話就可以使用line_profiler了,它可以偵測出每行程式碼的運行時間。

line_profiler是python的非標準函式庫,使用的使用pip的方式安裝一下。

pip install line_profiler

最簡單的使用方式直接將需要測試的函數加入即可。

def base_func3():
    for n in range(10000):
        print('当前n的值是:{}'.format(n))
from line_profiler import LineProfiler
lp = LineProfiler()
lp_wrap = lp(base_func3)
lp_wrap()
lp.print_stats()
# Line #      Hits         Time  Per Hit   % Time  Line Contents
# ==============================================================
#     72                                           def base_func3():
#     73     10001     162738.0     16.3      4.8      for n in range(10000):
#     74     10000    3207772.0    320.8     95.2          print('当前n的值是:{}'.format(n))

從運行結果可以看出每行程式碼的運行時間及比例,注意這裡的時間單位是微妙。

heartrate視覺化偵測

heartrate最值得推薦的是可以在網頁上針對偵測心率一樣偵測程式的執行過程,同時,他還是非標準函式庫,使用pip的方式進行安裝。

pip install heartrate
import heartrate
heartrate.trace(browser=True)
def base_func4():
    for n in range(10000):
        print('当前n的值是:{}'.format(n))

運行以後,控制台列印如下日誌:

#  * Serving Flask app "heartrate.core" (lazy loading)
#  * Environment: production
#    WARNING: This is a development server. Do not use it in a production deployment.
#    Use a production WSGI server instead.
#  * Debug mode: off

並且自動開啟瀏覽器位址:http://127.0.0.1:9999

python函數運行記憶體時間等效能檢測工具怎麼用

#

以上是python函數運行記憶體時間等效能檢測工具怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除