1

I would to know if their is a way to call a numpy function efficiently in a cython code ? It seems that the communication with python can be very costly in a loop.

Exemple:

import numpy as np

cimport numpy as np


cimport cython 
DTYPE = np.float
ITYPE = np.int
ctypedef np.float_t DTYPE_t
ctypedef np.int_t ITYPE_t


def func(A,B):
    return func_c(A,B)


@cython.cdivision(True) 
@cython.boundscheck(False)
@cython.wraparound(False)

cdef np.ndarray[DTYPE_t,ndim=2] func_c(np.ndarray[DTYPE_t,ndim=2] A,np.ndarray[DTYPE_t,ndim=2] B):


    cdef np.ndarray[DTYPE_t,ndim=2] P1=np.matrix(np.zeros((3,3)))

    for t in range(10):

        P1=np.linalg.inv(A) 
        P2=np.dot(P1,B)

    return P2
Marty
  • 53
  • 4
  • 2
    1) use blas-functionality directly (https://docs.scipy.org/doc/scipy-0.19.0/reference/linalg.cython_blas.html#module-scipy.linalg.cython_blas) 2) don't invert A in every iteration but once outside, or even better, don't invert it at all - https://en.wikipedia.org/wiki/LU_decomposition. – ead Feb 27 '20 at 20:16
  • Typing the variables is actually worse than non-typing them here. Typing only speeds up indexing operations in Cython - it doesn't speed up calls to Numpy functions. It does add a type check on every assignment though – DavidW Feb 28 '20 at 07:54
  • If you search on [stack overflow for "[cython] blas"](https://stackoverflow.com/search?q=%5Bcython%5D+blas) you can see quite a few examples of what you're trying to do – DavidW Feb 28 '20 at 07:58

0 Answers0