Return multiple values in cdef function

4,189 views
Skip to first unread message

Dzung Hong

unread,
Jan 14, 2011, 2:25:37 PM1/14/11
to cython-users
Hi all,

I have a function that returns multiple np.ndarray arrays. Is there
any way to write it using cdef rather than normal Python's def
function. For example, if I have to write it using Python's def:

import numpy as np
cimport numpy as np

def foo(np.ndarray[np.float64_t, ndim=1] a):
return a + 1, a +2

I want to speed it up by declaring the return type, since this
function will likely return a big matrix. Is that possible to convert
the above function to cdef function?

Thanks a lot,
Dzung

Robert Bradshaw

unread,
Jan 14, 2011, 4:34:48 PM1/14/11
to cython...@googlegroups.com
On Fri, Jan 14, 2011 at 11:25 AM, Dzung Hong <hongtr...@gmail.com> wrote:
> Hi all,
>
> I have a function that returns multiple np.ndarray arrays. Is there
> any way to write it using cdef rather than normal Python's def
> function. For example, if I have to write it using Python's def:
>
> import numpy as np
> cimport numpy as np
>
> def foo(np.ndarray[np.float64_t, ndim=1] a):
>  return a + 1, a +2

Yes, write

cdef foo(aa):
cdef np.ndarray[np.float64_t, ndim=1] a = aa


return a + 1, a + 2

(This is rather orthogonal--cdef functions can't take typed buffers
(yet). They can return multiple values, as a tuple, just like def
functions (but faster)).

> I want to speed it up by declaring the return type, since this
> function will likely return a big matrix. Is that possible to convert
> the above function to cdef function?

How will declaring the return type speed it up? Usually declaring the
return types speeds things up by avoiding the unnecessary wrapping of
C primitives in Python objects, but the numpy arrays are already
Python objects anyway. If it is really a big matrix, then the call
overhead is amortized and relatively tiny (depending on your
definition of big).

- Robert

Dzung Hong

unread,
Jan 15, 2011, 1:37:24 AM1/15/11
to cython-users
Thanks a bunch. It does help.

-Dzung

On Jan 14, 4:34 pm, Robert Bradshaw <rober...@math.washington.edu>
wrote:
Reply all
Reply to author
Forward
0 new messages