python雖然是一門'慢語言',但是也有著比較多的性能檢測工具來幫助我們優化程式的運行效率,
【閱讀全文】
這里總結了五個比較好的python性能檢測工具,包括記憶體使用、運行時間、執行次數等方面,
首先,來撰寫一個基礎的python函式用于在后面的各種性能測驗,
def base_func():
for n in range(10000):
print('當前n的值是:{}'.format(n))
1、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的記憶體,
2、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秒,
3、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))
從運行結果可以看出每行代碼的運行時間及比例,注意這里的時間單位是微妙,
4、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-turtle繪制雪容融,已打包成exe可直接運行(附原始碼)
如何將多張圖片合成mp4視頻格式,并加入背景音樂...
模型已經寫好了,怎么表白就看你的了!
python如何實作網路測驗,了解一下speedtest-cli...
又是櫻花盛開的季節,使用小烏龜來畫一顆櫻花樹吧!
歡迎關注作者公眾號【Python 集中營】,專注于后端編程,每天更新技術干貨,不定時分享各類資料!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/468728.html
標籤:Python
