python memory usage_Python - memory_profiler 内存分析工具

内存分析工具 Memory Profiler 是基于

安装:pip install -U memory_profiler

1. 逐行内存占用

在代码脚本外使用.

类似于 @profile 装饰要分析的函数;然后,使用特定脚本运行代码.

如:@profile

def my_func():

a = [1] * (10 ** 6)

b = [2] * (2 * 10 ** 7)

del b

return a

if __name__ == '__main__':

my_func()

运行:python -m memory_profiler example.py

输出如:Line # Mem usage Increment Occurences Line Contents

============================================================

3 38.816 MiB 38.816 MiB 1 @profile

4 def my_func():

5 46.492 MiB 7.676 MiB 1 a = [1] * (10 ** 6)

6 199.117 MiB 152.625 MiB 1 b = [2] * (2 * 10 ** 7)

7 46.629 MiB -152.488 MiB 1 del b

8 46.629 MiB 0.000 MiB 1 return a

其中,

第一列表示分析代码的行数;

第二列(Mem usage)表示执行完该行代码后 Python 解释器的内存使用;

第三列(Increment) 表示当前行和最后一行的内存占用差值;

第四列(Line Contents) 打印了待分析的代码.

2. 装饰器(Decorator)

在代码内使用.from memory_profiler import profile

@profile

#@profile(precision=4) 指定小数位.

def my_func():

a = [1] * (10 ** 6)

b = [2] * (2 * 10 ** 7)

del b

return a

运行:python example.py

Python程序的内存使用情况可以使用Python内置的`memory_profiler`模块进行监视。`memory_profiler`可以帮助我们分析Python程序的内存使用情况,找出内存泄漏等问题。 安装`memory_profiler`模块: ```python pip install memory_profiler ``` 使用`memory_profiler`监视Python程序的内存使用情况: 1. 在需要监视的函数上添加`@profile`装饰器。 2. 运行程序时加上`-m memory_profiler`参数,并指定要监视的文件名。 例如,我们有以下Python程序: ```python from random import randint @profile def generate_list(): nums = [randint(0, 100) for _ in range(1000000)] return nums if __name__ == '__main__': nums = generate_list() print(sum(nums)) ``` 我们可以在`generate_list()`函数上加上`@profile`装饰器,然后运行以下命令: ```python python -m memory_profiler memory_test.py ``` 输出结果: ``` Filename: memory_test.py Line # Mem usage Increment Line Contents ================================================ 3 52.5 MiB 52.5 MiB @profile 4 def generate_list(): 5 81.9 MiB 29.4 MiB nums = [randint(0, 100) for _ in range(1000000)] 6 81.9 MiB 0.0 MiB return nums 12671490 ``` 输出结果中,`Line #`表示代码行号,`Mem usage`表示该行执行后的内存使用情况,`Increment`表示相对于上一行的内存增加量,`Line Contents`表示该行代码内容。我们可以看到,在`generate_list()`函数中,内存使用量从52.5 MiB增加到81.9 MiB,增加了29.4 MiB,随着程序的执行结束,内存使用量又降回到了52.5 MiB。 通过`memory_profiler`模块的输出结果,我们可以找出Python程序中的内存泄漏和不必要的内存占用,从而进行优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值