Today I built a linspace
function in Python's C API:
static PyObject *
linspace(PyObject * self, PyObject * args)
{
int n, i;
double start, end;
if (!PyArg_ParseTuple(args, "ddi:linspace", &start, &end, &n))
return NULL;
if (n <= 1)
return Py_BuildValue("[d]", end);
double h;
PyObject *pylist = PyList_New(n);
h = (end - start) / (n - 1);
for (i = 0; i < n; i++)
PyList_SetItem(pylist, i, Py_BuildValue("d", (start + h * i)));
return Py_BuildValue("O", pylist);
}
It behaves how I would like it to behave, however, when I benchmarked it against NumPy's linspace
it was slower by about a factor of 80.
I have a few questions that I think may be affecting performance, but I can't seem to find help online:
- Is there a memory leak? Or am I not incrementing or decrementing any references that I should be?
- Can I do this with a C double array and then return that as a Python Object? Would this even be faster (I think it may)?
- Am I missing something? I am new to the C API and I am not confident in it yet.