%%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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With