New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C API for appending to arrays #49391
Comments
The array.array type is an excellent type for storing a large amount of This might seem superfluous, as it's perfectly possible to manipulate /* error checking and refcounting subtleties omitted for brevity */
PyObject *load_data(Source *src)
{
PyObject *array_type = get_array_type();
PyObject *array = PyObject_CallFunction(array_type, "c", 'd');
PyObject *append = PyObect_GetAttrString(array, "append");
while (!source_done(src)) {
double num = source_next(src);
PyObject *f = PyFloat_FromDouble(num);
PyObject *ret = PyObject_CallFunctionObjArgs(append, f, NULL);
if (!ret)
return NULL;
Py_DECREF(ret);
Py_DECREF(f);
}
Py_DECREF(array_type);
return array;
} The inner loop must convert each C double to a Python Float, only for Float creation is already well-optimized, so opportunities for speedup int array_append(PyObject *array, PyObject *appendfun, double val)
{
PyObject *ret;
double *buf;
Py_ssize_t bufsize;
static PyObject *zero;
if (!zero)
zero = PyFloat_FromDouble(0);
// append dummy zero value, created only once
ret = PyObject_CallFunctionObjArgs(appendfun, zero, NULL);
if (!ret)
return -1;
Py_DECREF(ret);
// append the element directly at the end of the C buffer
PyObject_AsWriteBuffer(array, (void **) &buf, &bufsize));
buf[bufsize / sizeof(double) - 1] = val;
return 0;
} This hack actually speeds up array creation by a significant percentage It turns out that an even faster method of creating an array is by using Would it be possible for the array module to define a C interface for |
Arrays already support the buffer interface |
Yes, and I use it in the second example, but the buffer interface |
I had a similar problem creating a C-fast array.array interface for Cython. |
This has more chances of seeing some progress if you propose a patch. |
A first thing would be to select a suitable prefix name for the Array In case sb goes into this: int
PyArr_ExtendFromBuffer(PyObject *arr, void* stuff, Py_ssize_t items) |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: