Cython: Should I use np.float_t rather than double

2019-02-16 23:08发布

问题:

Concerning memoryviews in cython, is there any advantage of typing a view with NumPy types such as np.float_t instead of simply do double if I'm working with numpy float arrays?

And should I type the cdef then the same way, doing e. g.

ctypedef np.float64_t np_float_t
...

@cython.profile(False)
@cython.wraparound(False)
@cython.boundscheck(False)
cdef np_float_t mean_1d(np_float_t [:] v) nogil:
    cdef unsigned int n = v.shape[0]
    cdef np_float_t n_sum = 0.

    cdef Py_ssize_t i
    for i in range(n):
        n_sum += v[i]

    return n_sum / n

回答1:

If you look in the numpy header file included with cython (e.g. in the master branch, it is __init__.pxd), you'll find

    ctypedef double       npy_double

and

ctypedef npy_double     float_t

In other words, float_t is double, so there should be no advantange to using np.float_t.