Repository navigation
Conversation
|
If a list writer is used by multiple threads, |
|
This C API is just an abstraction on top of existing PyList functions. |
Documentation build overview
227 files changed ·
|
|
Another advantage of using this C API instead of |
Oh, this failure seems to be unrelated to my change: |
|
I ran a benchmark to compare
I ran the benchmark on Free Threaded build on Linux ( import pyperf, functools, _testcapi
runner = pyperf.Runner()
sizes = (0, 10, 100, 1_000)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_setitem_macro, test_list)
runner.bench_time_func(f'setitem macro {list_len:,}-list', func)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_setitem_func, test_list)
runner.bench_time_func(f'setitem func {list_len:,}-list', func)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_writer, test_list)
runner.bench_time_func(f'writer {list_len:,}-list', func)Results:
On Free Threading, Patch adding 3 bench functions to _testcapi: Detailsdiff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c
index 033ee3234cf..a3a8d9989c0 100644
--- a/Modules/_testcapimodule.c
+++ b/Modules/_testcapimodule.c
@@ -2889,6 +2889,112 @@ uptime_bsd(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args))
#endif
+static PyObject*
+bench_setitem_macro(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyObject *result = PyList_New(len);
+ if (result == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = Py_NewRef(PyList_GET_ITEM(list, j));
+ PyList_SET_ITEM(result, j, item);
+ }
+
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_setitem_func(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyObject *result = PyList_New(len);
+ if (result == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = Py_NewRef(PyList_GET_ITEM(list, j));
+ if (PyList_SetItem(result, j, item) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_writer(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyListWriter *writer = PyListWriter_Create(len);
+ if (writer == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = PyList_GET_ITEM(list, j);
+ if (PyListWriter_Append(writer, item) < 0) {
+ PyListWriter_Discard(writer);
+ return NULL;
+ }
+ }
+
+ PyObject *result = PyListWriter_Finish(writer);
+ if (result == NULL) {
+ return NULL;
+ }
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
static PyMethodDef TestMethods[] = {
{"set_errno", set_errno, METH_VARARGS},
{"test_config", test_config, METH_NOARGS},
@@ -2988,6 +3094,9 @@ static PyMethodDef TestMethods[] = {
#ifdef HAVE_SYSCTLBYNAME
{"uptime_bsd", uptime_bsd, METH_NOARGS},
#endif
+ {"bench_setitem_macro", bench_setitem_macro, METH_VARARGS},
+ {"bench_setitem_func", bench_setitem_func, METH_VARARGS},
+ {"bench_writer", bench_writer, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
|
|
I also ran benchmarks on
Well, it's not surprising that Benchmark script: Detailsimport pyperf, functools, _testcapi
runner = pyperf.Runner()
sizes = (0, 10, 100, 1_000)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_setitem_macro, test_list)
runner.bench_time_func(f'setitem macro {list_len:,}-list', func)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_writer_append, test_list)
runner.bench_time_func(f'writer append {list_len:,}-list', func)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_writer_extend, test_list)
runner.bench_time_func(f'writer extend {list_len:,}-list', func)
for list_len in sizes:
test_list = list(range(list_len))
func = functools.partial(_testcapi.bench_writer_extend_array, test_list)
runner.bench_time_func(f'writer extend array {list_len:,}-list', func)Patch adding C benchmarks: Detailsdiff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c
index 033ee3234cf..c191d12c862 100644
--- a/Modules/_testcapimodule.c
+++ b/Modules/_testcapimodule.c
@@ -2889,6 +2889,185 @@ uptime_bsd(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args))
#endif
+static PyObject*
+bench_setitem_macro(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyObject *result = PyList_New(len);
+ if (result == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = Py_NewRef(PyList_GET_ITEM(list, j));
+ PyList_SET_ITEM(result, j, item);
+ }
+
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_setitem_func(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyObject *result = PyList_New(len);
+ if (result == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = Py_NewRef(PyList_GET_ITEM(list, j));
+ if (PyList_SetItem(result, j, item) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_writer_append(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyListWriter *writer = PyListWriter_Create(len);
+ if (writer == NULL) {
+ return NULL;
+ }
+
+ for (Py_ssize_t j=0; j < len; j++) {
+ PyObject *item = PyList_GET_ITEM(list, j);
+ if (PyListWriter_Append(writer, item) < 0) {
+ PyListWriter_Discard(writer);
+ return NULL;
+ }
+ }
+
+ PyObject *result = PyListWriter_Finish(writer);
+ if (result == NULL) {
+ return NULL;
+ }
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_writer_extend(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyListWriter *writer = PyListWriter_Create(len);
+ if (writer == NULL) {
+ return NULL;
+ }
+
+ if (PyListWriter_Extend(writer, list) < 0) {
+ PyListWriter_Discard(writer);
+ return NULL;
+ }
+
+ PyObject *result = PyListWriter_Finish(writer);
+ if (result == NULL) {
+ return NULL;
+ }
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject*
+bench_writer_extend_array(PyObject *Py_UNUSED(self), PyObject *args)
+{
+ PyObject *list;
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "On", &list, &loops)) {
+ return NULL;
+ }
+
+ PyObject **list_items = _PyList_CAST(list)->ob_item;
+ Py_ssize_t len = PyList_GET_SIZE(list);
+
+ PyTime_t t1, t2;
+ (void)PyTime_PerfCounterRaw(&t1);
+ for (Py_ssize_t i=0; i < loops; i++) {
+ PyListWriter *writer = PyListWriter_Create(len);
+ if (writer == NULL) {
+ return NULL;
+ }
+
+ if (PyListWriter_ExtendArray(writer, list_items, len) < 0) {
+ PyListWriter_Discard(writer);
+ return NULL;
+ }
+
+ PyObject *result = PyListWriter_Finish(writer);
+ if (result == NULL) {
+ return NULL;
+ }
+ Py_DECREF(result);
+ }
+ (void)PyTime_PerfCounterRaw(&t2);
+
+ return PyFloat_FromDouble(PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
static PyMethodDef TestMethods[] = {
{"set_errno", set_errno, METH_VARARGS},
{"test_config", test_config, METH_NOARGS},
@@ -2988,6 +3167,11 @@ static PyMethodDef TestMethods[] = {
#ifdef HAVE_SYSCTLBYNAME
{"uptime_bsd", uptime_bsd, METH_NOARGS},
#endif
+ {"bench_setitem_macro", bench_setitem_macro, METH_VARARGS},
+ {"bench_setitem_func", bench_setitem_func, METH_VARARGS},
+ {"bench_writer_append", bench_writer_append, METH_VARARGS},
+ {"bench_writer_extend", bench_writer_extend, METH_VARARGS},
+ {"bench_writer_extend_array", bench_writer_extend_array, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
|
|
+1 on the principle, this looks like a very useful addition. |
In release mode, no longer initialize items to NULL for better performance. The caller is responsible to initialize all items before calling PyListWriter_Finish().
Oh sure, there is no need to initialize items to NULL since the list is not tracked by the GC. I implemented this optimization.
I'm not sure how other C API Working Group members feel about functions stealing references. But ok, I added the function! |
|
I mark the PR as ready for review. |
|
@encukou: So what do you think of this APi? |
|
How important is this?
If there's a function that doesn't steal, it's fine to add an additional one with a Personally I'd prefer separating suffixes like this with an underscore ( |
Revert _Py_VaBuildArray() and memoryobject.c changes.
PyListWriter C APIPyListBuilder C API
|
I updated the PR:
|
old_size is only needed if _PyListBuilder_INIT_ITEMS is true.
* Inline _PyListBuilder_SET_ITEM_STEAL() in PyListBuilder_AppendSteal(). * Fix _PyListBuilder_Resize(): use "allocated" to initialize items to NULL. * builder_dealloc() calls PyListBuilder_Discard() even if the builder is NULL, to simplify the code. * list_new_prealloc(): don't check op->ob_item == NULL on Free Threading, list_allocate_array() failure is already checked. * Mark _PyListBuilder_Resize() and _PyListBuilder_ResetSize() as static.
|
@ngoldbaum @encukou @serhiy-storchaka: Would you mind to review the Some notes on the implementation:
|
Use again PyMem_New() since it checks for overflow. Also, initialize "op->ob_item = NULL;" if list_allocate_array() fails.
* Fix PyListBuilder_Extend() in debug mode: initialize newly allocated items to NULL. * PyListBuilder_AppendSteal() no longer checks if the item was already set. * PyListBuilder_ExtendArray() now raises SystemError if an array item is NULL in debug mode. * PyListBuilder_Finish() now fails with SystemError if an item is NULL. The error message gives the item index.
Always clear the array on error. Previously, only one error path was covered: two code paths didn't clear the array. Update PyListBuilder_ExtendArray(): mention that nitem must not be negative.
|
There is a performance issue: PyListBuilder_Extend() shrinks the list if it's "too large", so preallocated items are lost (deallocated). I propose fixing this issue in a separated PR to not make this PR too big. One option would be to add a Example:
The first A similar issue exists with import _testcapi, _testlimitedcapi
L = _testlimitedcapi.list_new(1_000)
_testlimitedcapi.pyset_size(L, 0)
print("after PyList_New(1000), allocated:", _testcapi._list_get_allocated(L))
L.extend(range(3))
print("after the first extend, allocated:", _testcapi._list_get_allocated(L))
L.extend(range(3, 1_000))
print("after the second extend, allocated:", _testcapi._list_get_allocated(L))Output: I modified _testlimited to add a |
serhiy-storchaka
left a comment
There was a problem hiding this comment.
Every branch of PyListBuilder_Extend() calls list_resize(self, m + n), which shrinks a list using less than half its allocation. So Create(1000) followed by Extend((1, 2, 3)) also drops the preallocation, not just the iterator path.
| if (res < 0) { | ||
| // On error, reset the builder to its previous state: | ||
| // discard added items | ||
| listbuilder_reset_size(builder, old_size); | ||
| } |
There was a problem hiding this comment.
Why is this needed? In most if not all case, the error will be followed by PyListBuilder_Discard(). Are there cases that need to keep already added items, but only these which were added before the current extend operation?
There was a problem hiding this comment.
PyUnicodeWriter has a similar design: operations are atomic, the writer/builder is restored to its previous state on error. For a list builder, it means that added items are discarded on error. So you can still continue using a writer/builder after an error, since it's in a well defined state. I'm not sure that it's really needed, but it's not hard to implement and it might be useful to some use cases.
There was a problem hiding this comment.
On the other side, PySetBuilder cannot implement atomic operations in an efficient way, so I propose suggesting to discard the builder on error: see "Add and Update are not atomic" section of capi-workgroup/decisions#119.
Use Py_XDECREF() instead of Py_DECREF(). Add tests on PyListBuilder_ExtendArray() and PyListBuilder_ExtendArraySteal() with NULL items.
Replace also "On Free Threading" with "On the free-threaded build".
Right. See my previous comment #160127 (comment). I propose to fix this performance issue in a followup PR. |
|
@serhiy-storchaka: I addressed most of your suggestions, please review the updated PR. |
I don't think a separate PR is necessary for listbuilder_resize I agree that changing Extend would be best as another PR. |
Co-authored-by: Petr Viktorin <encukou@gmail.com>
IMO I prefer to change it in a separated issue and PR. It does fix the PyListBuilder performance issue. I suppose that no one reported the performance issue so far since calling |
|
@encukou: Thanks with your suggestions to enhance the documentation. I agree with them, so I applied all of them. Please review the updated PR. |

PyList_SetItemis ~2.7x slower per item on the free-threaded build #158660