memory_profiler 怎么使用
时间: 2023-09-02 08:11:41 浏览: 164
1. 安装 memory_profiler
使用 pip 安装 memory_profiler:
```
pip install memory_profiler
```
2. 编写代码
假设我们要测试以下代码的内存使用情况:
```
# test.py
import time
def func():
a = [i for i in range(1000000)]
time.sleep(1)
return a
if __name__ == '__main__':
func()
```
3. 使用 memory_profiler 进行测试
在命令行中输入以下命令:
```
python -m memory_profiler test.py
```
运行结果如下:
```
Filename: test.py
Line # Mem usage Increment Line Contents
================================================
3 29.469 MiB 29.469 MiB def func():
4 133.496 MiB 104.027 MiB a = [i for i in range(1000000)]
5 133.496 MiB 0.000 MiB time.sleep(1)
6 133.496 MiB 0.000 MiB return a
```
其中,Mem usage 列是该行代码执行后的内存占用情况,Increment 列是该行代码执行后增加的内存占用量。
4. 使用 @profile 装饰器
在代码中使用 @profile 装饰器可以对指定的函数进行内存分析。
```
from memory_profiler import profile
import time
@profile
def func():
a = [i for i in range(1000000)]
time.sleep(1)
return a
if __name__ == '__main__':
func()
```
在命令行中运行以下命令:
```
python test.py
```
运行结果如下:
```
Line # Mem usage Increment Line Contents
================================================
5 29.6 MiB 29.6 MiB @profile
6 def func():
7 29.6 MiB 0.0 MiB a = [i for i in range(1000000)]
8 33.5 MiB 3.9 MiB time.sleep(1)
9 33.5 MiB 0.0 MiB return a
```
阅读全文
相关推荐















