On Mar 24, 2009, at 9:20 PM, Brett Calcott wrote:

> Hi,
>
> I've just whipped up my first cython-based code to try and speed up
> some operations on some numpy-based code I'm writing. It works, but
> I'd like to know how to make it go faster. It basically does something
> like bincount (though bincount does not appear to work on more than
> 1-dimension).
>
> I've looked at the resulting C code and cannot understand why (in some
> cases) there are still some pythonic calls being made. Any help would
> be appreciated. Some questions are in the code (and yes, it assumes
> that bounds checking is done before the call)
>
> import numpy as np
> cimport numpy as np
> cimport cython
>
> @cython.boundscheck(False) # turn of bounds-checking for entire  
> function
> def table_bincount(int max_elements, np.ndarray[long, ndim=2] table):
>     cdef long rows = table.shape[0]
>     cdef long columns = table.shape[1]
>     cdef long i, j
>     cdef np.ndarray[double, ndim=2] retval = np.zeros(
>             (rows, max_elements), dtype=np.float64)
>
>     for 0 <= i < rows:
>         # Is there any way of typing these intermediate values so  
> that they
>         # do not get turned into python code?
>         current_in_row = table[i]
>         current_out_row = retval[i]
>         for 0 <= j < columns:
>             current_out_row[current_in_row[j]] += 1
>             # Notice that even if do this instead :
>             # retval[i][table[i, j]] += 1
>             # ... it still generates some pythonic stuff like
>             # PyNumberAddInplace
>
>     return retval

This is because you're writing retval[i][table[i, j]] += 1 rather  
than retval[i, table[i, j]] += 1. (I think this was already mentioned.)

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to