Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster : Zeroing cython array

Tags:

fill

zero

cython

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

like image 563
sten Avatar asked Sep 25 '26 21:09

sten


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.

like image 100
DavidW Avatar answered Sep 28 '26 20:09

DavidW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!