Declaring a numpy array and c-pointer in cython

In my code, I usually use numpy arrays to interact between methods and classes. Optimizing the main parts of my program, I use cython with c pointers to these numpy arrays. Unfortunately, the way I'm declaring arrays right now is pretty long.

For example, let's say I have a method that should return a numpy array someArrayNumpy, but inside the function pointers * someArrayPointers should be used for speed. Here is how I usually declare it:

cdef: numpy.ndarray someArrayNumpy = numpy.zeros(someArraySize) numpy.ndarray[numpy.double_t, ndim=1] someArrayBuff = someArrayNumpy double *someArrayPointers = <double *> someArrayBuff.data [... some Code ...] return someArrayNumpy 

As you can see, this takes 3 lines of code for basically one array, and often I have to declare more of these arrays.

Is there a more compact / smart way to do this? I think something is missing.

EDIT:

So, because it was set by J. Martinot-Lagarde, I timed C-pointers and "numpy pointers". The code was basically

 for ii in range(someArraySize): someArrayPointers[ii] += 1 

and

 for ii in range(someArraySize): someArrayBuff[ii] += 1 

with the definitions above, but I added "ndim = 1, mode = 'c" to make sure. Results for someArraySize = 1e8 (time in ms):

 testMartinot("cPointers") 531.276941299 testMartinot("numpyPointers") 498.730182648 

What I roughly remember from previous / different tests.

+7
python numpy cython
source share
1 answer

You actually declare two numpy arrays here, the first of them is common, and the second has a specific type of dtype. You can skip the first line, someArrayBuff is ndarray.

This gives:

 numpy.ndarray[numpy.double_t] someArrayNumpy = numpy.zeros(someArraySize) double *someArrayPointers = <double *> someArrayNumpy.data 

You need at least two lines because you use someArrayPointers and return someArrayNumpy, so you need to declare them.


As you noticed, are you sure pointers are faster than ndarrays if you declare the type and number of dimensions of an array?

 numpy.ndarray[numpy.double_t, ndim=2] someArrayNumpy = numpy.zeros(someArraySize) 
+5
source share

All Articles