[issue2898] Add memory footprint query

Robert Schuppenies report at bugs.python.org
Thu Jun 19 00:10:53 CEST 2008

Robert Schuppenies <okkotonushi at googlemail.com> added the comment:

Jean Brouwers wrote:
> 1) In the first line of function  dict_sizeof()
> +	res = sizeof(PyDictObject) + sizeof(mp->ma_table);
> is the  sizeof(mp->ma_table) counted twice?

Yes, you are right. I'll fix this. 

> 2) Since functions  list_sizeof and  dict_sizeof return the allocated 
> size, including the over-allocation, should function  string_sizeof not 
> include the sentinel null character?

Isn't this addressed by taking PyStringObject.ob_sval into account? It
is allocated with 1 char length and thus always included. If I
understand the creation of strings correctly, the corresponding memory
is always allocated with

PyObject_MALLOC(sizeof(PyStringObject) + size)

which should mean that the space for the null terminating character is
included in the sizeof(PyStringObject).

> 3) Are tuples left out on purpose?  

No, that slipped the initial patch. I corrected in r64230. 

> ....
> static PyObject *
> tuple_sizeof(PyTupleObject *v)
> {
> 	Py_ssize_t res;
> 	res = _PyObject_SIZE(&PyTuple_Type) + Py_SIZE(v) * 
> sizeof(void*);
> 	return PyInt_FromSsize_t(res);
> }
> ....

Your implementation is like the applied changes from me, with one
difference. The basicsize of a tuple is defined as
"sizeof(PyTupleObject) - sizeof(PyObject *)"

When a tuple's memory is allocated, the required space is computed
roughly like this

(typeobj)->tp_basicsize + (nitems)*(typeobj)->tp_itemsize

Thus, I understand the memory allocated by a tuple to be

res = PyTuple_Type.tp_basicsize + Py_SIZE(v) * sizeof(PyObject *);

Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list