python分配大内存_python-为大型对象分配名称似乎会大大增加内存使用量

通常,当我需要调用一个复杂的公式时,我会将其分解为两行或更多行,以使代码更易于理解.但是,在分析一些计算出RMSE的代码时,我发现这样做似乎会增加代码的内存使用量.这是一个简化的示例:

import numpy as np

import random

from memory_profiler import profile

@profile

def fun1():

#very large datasets (~750 mb each)

predicted = np.random.rand(100000000)

observed = np.random.rand(100000000)

#calculate residuals as intermediate step

residuals = observed - predicted

#calculate RMSE

RMSE = np.mean(residuals **2) ** 0.5

#delete residuals

del residuals

@profile

def fun2():

#same sized data

predicted = np.random.rand(100000000)

observed = np.random.rand(100000000)

#same calculation, but with residuals and RMSE calculated on same line

RMSE = np.mean((observed - predicted) ** 2) ** 0.5

if __name__ == "__main__":

fun1()

fun2()

输出:

Filename: memtest.py

Line # Mem usage Increment Line Contents

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

5 19.9 MiB 0.0 MiB @profile

6 def fun1():

7 782.8 MiB 763.0 MiB predicted = np.random.rand(100000000)

8 1545.8 MiB 762.9 MiB observed = np.random.rand(100000000)

9 2308.8 MiB 763.0 MiB residuals = observed - predicted

10 2308.8 MiB 0.1 MiB RMSE = np.mean(residuals ** 2) ** 0.5

11 1545.9 MiB -762.9 MiB del residuals

Filename: memtest.py

Line # Mem usage Increment Line Contents

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

13 20.0 MiB 0.0 MiB @profile

14 def fun2():

15 783.0 MiB 762.9 MiB predicted = np.random.rand(100000000)

16 1545.9 MiB 762.9 MiB observed = np.random.rand(100000000)

17 1545.9 MiB 0.0 MiB RMSE = np.mean((observed - predicted) **

2) ** 0.5

如您所见,第一个函数(其中的计算被拆分)似乎需要额外的〜750 mb峰值,大概是残差数组的成本.但是,这两个函数都需要创建数组-唯一的区别是第一个函数为其分配了一个名称.这与我对python中内存管理应该起作用的方式的理解背道而驰.

那么,这是怎么回事?一种想法是,这可能是memory_profiler模块的某些工件.在运行期间监视Windows任务管理器会显示类似的模式(尽管我知道这不是一个非常值得信赖的验证).如果这是“真实的”效果,那么我对内存处理方式的误解是什么?或者,这是某种特定于numpy的吗?

解决方法:

memory_profiler的“内存使用情况”列告诉您每行完成后的内存使用情况,而不是该行期间的内存使用高峰.在不保存残差的版本中,该行在行完成之前就被丢弃,因此它永远不会显示在探查器输出中.

标签:python-2-7,memory-profiling,memory-management,python,numpy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值