Estimating memory use?

MrJean1 MrJean1 at gmail.com
Sun Nov 27 16:26:36 EST 2005


There is a function mx_sizeof() in the mx.Tools module from eGenix
which may be helpful.  More at


<http://www.egenix.com/files/python/eGenix-mx-Extensions.html#mxTools>

/Jean Brouwers


PS) This is an approximation for memory usage which is useful in
certain, simple cases.

Each built-in type has an attribute __basicsize__ which is the size in
bytes needed to represent the basic type.  For example
str.__basicsize__ returns 24 and int.__basictype__ returns 12.

However, __basicsize__ does not include the space needed to store the
object value.  For a string, the length of the string has to be added
(times the character width).  For example, the size of string "abcd"
would at least approximately str.__basicsize__ + len("abcd") bytes,
assuming single byte characters.

In addition, memory alignment should be taken into account by rounding
the size up to the next multiple of 8 (or maybe 16, depending on
platform, etc.).

An approximation for the amount of memory used by a string S (of single
byte characters) aligned to A bytes would be

   (str.__basicsize__  +  len(S)  +  A - 1)  &  A

Things are more complicated for types like list, tuple and dict and
instances of a class.




More information about the Python-list mailing list