Skip to content

Commit ce19aa4

Browse files
committed
Fix queue.SimpleQueue.__sizeof__() to account for buffer
Fixes #140025 The __sizeof__() method for queue.SimpleQueue previously ignored the underlying RingBuf data structure, only returning the basic object size. Now properly accounts for the dynamically allocated items array in the RingBuf, which grows with the queue capacity: - Returns base object size + (items_cap * sizeof(PyObject*)) This gives accurate memory usage for SimpleQueue instances.
1 parent b6b0e14 commit ce19aa4

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

Modules/_queuemodule.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,15 @@ queue_free(void *m)
524524
(void)queue_clear((PyObject *)m);
525525
}
526526

527+
static PyObject *
528+
simplequeue_sizeof(simplequeueobject *self, PyObject *Py_UNUSED(ignored))
529+
{
530+
Py_ssize_t res = _PyObject_SIZE(Py_TYPE(self));
531+
// Add size of the RingBuf items array
532+
res += self->buf.items_cap * sizeof(PyObject *);
533+
return PyLong_FromSsize_t(res);
534+
}
535+
527536
#include "clinic/_queuemodule.c.h"
528537

529538

@@ -534,6 +543,8 @@ static PyMethodDef simplequeue_methods[] = {
534543
_QUEUE_SIMPLEQUEUE_PUT_METHODDEF
535544
_QUEUE_SIMPLEQUEUE_PUT_NOWAIT_METHODDEF
536545
_QUEUE_SIMPLEQUEUE_QSIZE_METHODDEF
546+
{"__sizeof__", (PyCFunction)simplequeue_sizeof,
547+
METH_NOARGS, PyDoc_STR("Return the size of the SimpleQueue in memory, in bytes.")},
537548
{"__class_getitem__", Py_GenericAlias,
538549
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
539550
{NULL, NULL} /* sentinel */

0 commit comments

Comments
 (0)