numpy数组的Python内存使用情况 [英] Python memory usage of numpy arrays

查看:195
本文介绍了numpy数组的Python内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python分析一些大文件,并且遇到了内存问题,因此我一直在使用sys.getsizeof()来跟踪使用情况,但是numpy数组的行为很奇怪.这是一个涉及我必须打开的反照率地图的示例:

I'm using python to analyse some large files and I'm running into memory issues, so I've been using sys.getsizeof() to try and keep track of the usage, but it's behaviour with numpy arrays is bizarre. Here's an example involving a map of albedos that I'm having to open:

>>> import numpy as np
>>> import struct
>>> from sys import getsizeof
>>> f = open('Albedo_map.assoc', 'rb')
>>> getsizeof(f)
144
>>> albedo = struct.unpack('%df' % (7200*3600), f.read(7200*3600*4))
>>> getsizeof(albedo)
207360056
>>> albedo = np.array(albedo).reshape(3600,7200)
>>> getsizeof(albedo)
80

数据仍然存在,但是对象的大小(3600x7200像素图)已从约200 Mb变为80字节.我希望我的内存问题能够解决,然后将所有内容都转换为numpy数组,但是我认为这种行为(如果为真)将在某种程度上违反某些信息论或热力学定律,或者某些东西,所以我倾向于相信getsizeof()不适用于numpy数组.有什么想法吗?

Well the data's still there, but the size of the object, a 3600x7200 pixel map, has gone from ~200 Mb to 80 bytes. I'd like to hope that my memory issues are over and just convert everything to numpy arrays, but I feel that this behaviour, if true, would in some way violate some law of information theory or thermodynamics, or something, so I'm inclined to believe that getsizeof() doesn't work with numpy arrays. Any ideas?

推荐答案

您可以使用

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

这篇关于numpy数组的Python内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆