Faster : Zeroing cython array

Viewed 124

I'm using this to cleanup array in Cython

cdef void fill(DTYPE[:] ary):
    cdef int i, size = len(ary)
    for i in range(size): ary[i] = 0

is there a faster way ?


they seems to have it,cdef'd

source

cdef inline void zero(array self):
    """ set all elements of array to zero. """
    memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)

generated code :

    cdef array.array rows
    array.zero(rows)

__pyx_f_7cpython_5array_zero(__pyx_v_rows);

but if :

    cdef float[::1] rows

@DavidW example generates a cleaner version i.e. for-loop


summarized it here and added some more tricks

1 Answers
cdef void fill(double[:] ary):
    ary[:] = 0

compiles. It's certainly the clearest way and is converted to a straightforward looking C loop. It also means that you don't have to worry about turning off boundschecking and negative indexing.

It'll be helped a little if you declare ary as contiguous (double[::1] ary), although of course that restricts the types of arrays it can do. If you aren't prepared to only accept contiguous arrays, then you should not use memset since it'll be zeroing stuff outside your array.

Related