如何知道数组和字典之类的python对象的字节大小? -简单的方法 [英] How to know bytes size of python object like arrays and dictionaries? - The simple way

查看:443
本文介绍了如何知道数组和字典之类的python对象的字节大小? -简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种简单的方法来了解数组和字典对象的字节大小,例如

I was looking for a easy way to know bytes size of arrays and dictionaries object, like

[ [1,2,3], [4,5,6] ] or { 1:{2:2} }

许多主题都说要使用pylab,例如:

Many topics say to use pylab, for example:

from pylab import *

A = array( [ [1,2,3], [4,5,6] ] )
A.nbytes
24

但是,字典呢? 我看到很多建议使用pysize或heapy的答案. Torsten Marek在以下链接中给出了一个简单的答案:建议使用哪种Python内存探查器?,但是我由于字节数不匹配,因此对输出没有清晰的解释.

But, what about dictionaries? I saw lot of answers proposing to use pysize or heapy. An easy answer is given by Torsten Marek in this link: Which Python memory profiler is recommended?, but I haven't a clear interpretation about the output because the number of bytes didn't match.

Pysize似乎更复杂,我还不清楚如何使用它.

Pysize seems to be more complicated and I haven't a clear idea about how to use it yet.

鉴于我想执行的大小计算简单(无类,无复杂结构),关于简单方法来大致估计此类对象的内存使用量的任何想法吗?

Given the simplicity of size calculation that I want to perform (no classes nor complex structures), any idea about a easy way to get a approximate estimation of memory usage of this kind of objects?

亲切的问候.

推荐答案

有:

>>> import sys
>>> sys.getsizeof([1,2, 3])
96
>>> a = []
>>> sys.getsizeof(a)
72
>>> a = [1]
>>> sys.getsizeof(a)
80

但是我不会说那是可靠的,因为Python每个对象都有开销,并且有些对象除了引用其他对象外什么都不包含,因此与C语言和其他语言不太一样.

But I wouldn't say it's that reliable, as Python has overhead for each object, and there are objects that contain nothing but references to other objects, so it's not quite the same as in C and other languages.

已阅读 sys.getsizeof 上的文档,然后从那里去.

Have a read of the docs on sys.getsizeof and go from there I guess.

这篇关于如何知道数组和字典之类的python对象的字节大小? -简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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