Cython: Should I use np.float_t rather than double for typed memory views
Asked Answered
L

1

9

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
Local answered 7/1, 2014 at 18:20 Comment(0)
R
17

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.

Riley answered 7/1, 2014 at 22:47 Comment(5)
I found it.. line 311/758 :| and as we are about usage of types: (Why / When) Is it preferable to use Py_ssize_t for indexing? (In the docs I just found '# Purists could use "Py_ssize_t" which is the proper Python type for array indices.') -> does that mean always when indexing NumPy/Cython-Array(s)/-views whatever..?Local
Instead of a comment, you should start a new question about using Py_ssize_t. That will ensure it gets the most exposure.Riley
You're right. Easier also to find for other answer seekers. Mostly I'm doubtful whether it's worth to make an independent question out of it. However, I'll endeavour to do so from now onLocal
I made the Py_ssize_t thingy a new questionLocal
OK. I was just about the comment here that the answer is "yes"--but it is hard to find a definitive statement of this.Riley

© 2022 - 2024 — McMap. All rights reserved.