How to make 2d array fast in cython

32 views
Skip to first unread message

Raphael C

unread,
Dec 23, 2016, 8:48:51 AM12/23/16
to cython-users
I have some code which I am trying to make fast using cython. It takes in a numpy 2d array of floating point numbers and outputs a floating point number.  Here is my attempted so far.

from __future__ import division
import numpy as np
cimport numpy as np

DTYPE_int = np.int
ctypedef np.int_t DTYPE_int_t
DTYPE_float = np.float64
ctypedef np.float64_t DTYPE_float_t

def permfunc(np.ndarray [DTYPE_float_t, ndim =2] M):
    cdef int n = M.shape[0]
    cdef np.ndarray[DTYPE_int_t, ndim =1] d = np.ones(n, dtype=DTYPE_int)
    cdef int j =  0
    cdef int s = 1
    cdef np.ndarray [DTYPE_int_t, ndim =1] f = np.arange(n, dtype=DTYPE_int)
    cdef np.ndarray [DTYPE_float_t, ndim =1] v = M.sum(axis=0)
    cdef double p = 1
    cdef int i
    cdef double prod
    for i in range(n):
        p *= v[i]
    while (j < n-1):
        for i in range(n):
            v[i] -= 2*d[j]*M[j][i]
        d[j] = -d[j]
        s = -s
        prod = 1
        for i in range(n):
            prod *= v[i]
        p += s*prod
        f[0] = 0
        f[j] = f[j+1]
        f[j+1] = j+1
        j = f[0]
    return p/2**(n-1)    



Unfortunately it is still slower than just using pypy!    Looking at the output of cython -a  I see that this line

v[i] -= 2*d[j]*M[j][i]

is still being interpreted in python which I assume is what is causing the slowdown.

How can I fix that?


Raphael
Reply all
Reply to author
Forward
0 new messages