getting the size of an object

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jun 18 22:43:26 EDT 2007


En Mon, 18 Jun 2007 16:48:36 -0300, filox <filox_realmmakniovo at yahoo.com>  
escribió:
> "Brett Hoerner" <bretthoerner at bretthoerner.com> wrote in message

>> Although I have the feeling you mean "how many bytes does this object
>> take in memory" - and I believe the short answer is no.
>
> is there a long answer? what i want is to find out the number of bytes  
> the
> object takes up in memory (during runtime). since python has a lot of
> introspection mechanisms i thought that should be no problem...

Consider this:

x = "x" * 1000000

x is a string taking roughly 1MB of memory.

y = x

y is a string taking roughly 1MB of memory *but* it is shared, in fact it  
is the same object. So you can't add them to get the total memory usage.

z = (x,y)

z takes just a few bytes: a pointer to x, to y, to its own type, its  
reference count. The total memory for the three objects is a few bytes  
more than 1MB.

For arbitrary objects, a rough estimate may be its pickle size:
len(dumps(x)) == 1000008
len(dumps(y)) == 1000008
len(dumps(z)) == 1000016

-- 
Gabriel Genellina




More information about the Python-list mailing list