Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call np.sqrt in cython

%%cython
import numpy as np
cimport numpy as np

def cy_sum(int n):
    cdef double s=0
    cdef int i 
    for i in range(n):
        s += np.sqrt(i)
    return s

cython -a

I have the code for calculating the sum of square root as above. By using cython -a, I got the result as in the picture. The cython code interacts with python at function call np.sqrt(i), and there is no improvement compared to pure python code.

I don't know if I have done something wrong in specifying the type of variables. There are other solutions, such as using i**(1/2) or import the function sqrt from clib, but I would like to understand why cython cannot compile np.sqrt in this case.

Thank you.

like image 859
user1210321 Avatar asked Nov 08 '18 20:11

user1210321


1 Answers

In general, when Cython sees a python function call, it is treated as an opaque operation. Cython might elide a bit of calling overhead, but otherwise it will generate the exact same semantics as if that function was called from python.

Certain numpy constructs, such as the ndarray[dtype] type are special cased by the Cython compiler to generate more efficient code. numpy ufuncs are not, so to cython np.sqrt is just another python function, so it can do nothing better than calling back into python to run it.

Other python accelerators, such as numba will intercept the call to np.sqrt and rewrite it to the equivalent low level code.

like image 198
chrisb Avatar answered Sep 22 '22 10:09

chrisb