Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array with cython

I'm trying to port some python code to cython and I'm encountering some minor problems.

Below you see a code snippet (simplified example) of the code.

cimport numpy as np
cimport cython
@cython.boundscheck(False) # turn of bounds-checking for entire function
@cython.wraparound(False)
@cython.nonecheck(False)
def Interpolation(cells, int nmbcellsx):
    cdef np.ndarray[float,ndim=1] celle
    cdef int cellnonzero
    cdef int i,l
    for i in range(nmbcellsx):
          celle = cells[i].e
          cellnonzero = cells[i].nonzero
          for l in range(cellnonzero):
               celle[l] = celle[l] * celle[l]

I don't understand why the inner-most loop does not fully translate to C code (i.e. the last line, celle[l] = ...), see output from cython -a feedback:

enter image description here

What am I missing here?

Thanks a lot.

like image 911
user1829358 Avatar asked Jan 06 '13 15:01

user1829358


People also ask

Can you use NumPy with Cython?

You can use NumPy from Cython exactly the same as in regular Python, but by doing so you are losing potentially high speedups because Cython has support for fast access to NumPy arrays.

Why Cython is not popular?

One good reason is that it is a pure compiler and this is just not as easy to use during development. Another good reason is that it just isn't core Python - CPython is the real thing. You can simply put Cython into the same basket as all the other alternatives - Jython, a Java JVM implemention; IronPython, a C# .

Is Numba better than Cython?

The Takeaway. So numba is 1000 times faster than a pure python implementation, and only marginally slower than nearly identical cython code. There are some caveats here: first of all, I have years of experience with cython, and only an hour's experience with numba.

How much faster is Cython?

When Cython encounteres Python code it can't translate completely into C, it transforms that code into a series of C calls to Python's internals. This amounts to taking Python's interpreter out of the execution loop, which gives code a modest 15 to 20 percent speedup by default.


1 Answers

I finally realized that a simple "return 0" at the very end of the function solves this problem. However, this behaviour seems quite strange to me. Is this actually a bug?

like image 96
user1829358 Avatar answered Oct 06 '22 03:10

user1829358