Posts

Showing posts with the label attributes

Cython: size attribute of memoryviews

Image
Clash Royale CLAN TAG #URR8PPP Cython: size attribute of memoryviews I'm using a lot of 3D memoryviews in Cython, e.g. cython.declare(a='double[:, :, ::1]') a = np.empty((10, 20, 30), dtype='double') I often want to loop over all elements of a . I can do this using a triple loop like a for i in range(a.shape[0]): for j in range(a.shape[1]): for k in range(a.shape[2]): a[i, j, k] = ... If I do not care about the indices i , j and k , it is more efficient to do a flat loop, like i j k cython.declare(a_ptr='double*') a_ptr = cython.address(a[0, 0, 0]) for i in range(size): a_ptr[i] = ... Here I need to know the number of elements ( size ) in the array. This is given by the product of the elements in the shape attribute, i.e. size = a.shape[0]*a.shape[1]*a.shape[2] , or more generally size = np.prod(np.asarray(a).shape) . I find both of these ugly to write, and the (albeit small) computational overhead bothers me. The nice way to do...