分 3 步 ;)
第一步:安装line_profiler
pip install line_profiler
第 2 步:将@profile 添加到您的代码中:
from time import sleep
@profile
def so_slow(bar):
sleep(5)
return bar
if __name__ == "__main__":
so_slow(5)
第 3 步:测试您的代码:
kernprof -l -v your_code.py
结果
Wrote profile results to your_code.py.lprof
Timer unit: 1e-06 s
Total time: 5.00283 s
File: your_code.py
Function: so_slow at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 @profile
5 def so_slow(bar):
6 1 5002830 5002830.0 100.0 sleep(5)
7 1 2 2.0 0.0 return bar
memory_profiler
您也可以使用memory_profiler,安装它,添加配置文件并调用它:
pip install memory_profiler
python -m memory_profiler your_code.py
结果:
Filename: your_code.py
Line # Mem usage Increment Line Contents
================================================
4 21.289 MiB 0.000 MiB @profile
5 def so_slow(bar):
6 21.289 MiB 0.000 MiB sleep(5)
7 21.289 MiB 0.000 MiB return bar
更新:
您可以使用objgraph 查找memory leak 或绘制您的代码图:
from time import sleep
import objgraph
x = [1]
objgraph.show_backrefs([x], filename='sample-backref-graph.png')
def so_slow(bar):
sleep(5)
return bar
if __name__ == "__main__":
so_slow(5)
结果:
参考:A guide to analyzing Python performance