Python效能分析
在Python中,效能分析是衡量程式不同部分效能的過程,用於檢查和識別最佳化區域和瓶頸。我們有很多工具可以對Python程式碼進行效能分析,包括內建模組、庫和IDE(整合開發環境)。Python程式碼的效能分析有多種型別,讓我們逐一看看。
使用行效能分析
行效能分析是一種用於測量程式每一行程式碼執行時間的技術。它可以幫助我們識別哪些行程式碼佔用更多執行時間,以及找出程式碼中的緊密迴圈或其他關鍵效能部分。在Python中,可以使用line_profiler工具進行行效能分析。
首先,我們需要使用下面的程式碼行在我們的Python環境中安裝Line_profiler工具。
pip install line_profiler
輸出
Collecting line_profilerNote: you may need to restart the kernel to use updated packages.
Downloading line_profiler-4.0.3-cp39-cp39-win_amd64.whl (83 kB)
---------------------------------------- 83.6/83.6 kB 1.6 MB/s eta 0:00:00
Installing collected packages: line_profiler
Successfully installed line_profiler-4.0.3
現在,要使用line_profiler工具檢查給定Python程式碼的效能分析,語法如下。
import line_profiler line_profiler(python_code)
示例
在這個例子中,我們將使用line_profiler()工具檢查每一行程式碼的執行時間。此模組將Python程式碼作為輸入,並使用print_stats()函式返回時間作為輸出。
from line_profiler import LineProfiler
def add(a,b):
out = a + b
print("The sum of a and b:", out)
out = LineProfiler(add(10,30))
out.print_stats()
輸出
Using Function profiling
使用函式效能分析
函式效能分析是一種允許你測量程式中單個函式或方法執行時間的技術。這可以幫助我們識別哪些函式佔用最多的執行時間,也有助於在更高層次上最佳化程式碼。Python中用於函式效能分析的一個內建模組是cProfile。
cProfile模組的run()函式計算使用者定義函式的執行時間。
語法
以下是使用cProfile.run()的語法。
cProfile.run(function_name)
示例
在這個例子中,我們嘗試將函式名以字串格式傳遞給cProfile模組的run()函式,然後它返回所有執行統計資訊。
import cProfile
a = input("Enter the text to be displayed: ")
def display(a):
print(a)
cProfile.run('display')
輸出
Enter the text to be displayed: Welcome to Tutorialspoint.com
3 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
使用記憶體效能分析
記憶體效能分析是另一種技術,它可以幫助使用者測量程式在執行期間使用的記憶體量。這可以幫助我們識別記憶體洩漏或其他影響程式碼效能的記憶體相關問題。
memory_profiler模組中有一個profile()函式,它可以執行記憶體使用量的測量。
如果我們第一次使用此模組,則需要使用以下程式碼在Python環境中安裝它。
pip install memory_profiler
安裝後將顯示訊息:Collecting memory_profiler
Downloading memory_profiler-0.61.0-py3-none-any.whl (31 kB) Requirement already satisfied: psutil in c:\users\niharikaa\anaconda3\lib\site-packages (from memory_profiler) (5.9.0) Installing collected packages: memory_profiler Successfully installed memory_profiler-0.61.0
語法
使用memory_profiler的語法如下。
python -m memory_profiler file_name mprof run file_name
示例
如果我們想獲取已執行程式碼的記憶體效能分析統計資訊,則必須建立一個Python檔案,然後需要在命令提示符中透過傳遞Python檔案以及memory_profiler來執行。
以下是儲存在python_sample.py檔案中的程式碼。
from memory_profiler import profile @profile def display(): a = "Welcome to the Tutorialspoint website" print(a) display()
我們需要在命令提示符中執行以下程式碼行才能獲得記憶體統計資訊。
mprof run python_sample.py
輸出
mprof: Sampling memory every 0.1s running new process running as a Python program...
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP