Skip to content

Instantly share code, notes, and snippets.

@zonca
Created May 24, 2012 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonca/2784725 to your computer and use it in GitHub Desktop.
Save zonca/2784725 to your computer and use it in GitHub Desktop.
Cython Numpy accumulate
cimport numpy as np
ctypedef np.long_t DTYPE_int_t
ctypedef np.double_t DTYPE_double_t
cimport cython
@cython.boundscheck(False) # turn of bounds-checking for entire function
@cython.wraparound(False)
def accumulate(
np.ndarray[DTYPE_double_t, ndim=1] a not None,
np.ndarray[DTYPE_int_t, ndim=1] section_lengths not None,
np.ndarray[DTYPE_double_t, ndim=1] out not None,
):
cdef unsigned int i_el, i_bas, sec_length, lenout
cdef double tmp
lenout = out.shape[0]
i_el = 0
for i_bas in range(lenout):
tmp = 0
for sec_length in range(section_lengths[i_bas]):
tmp += a[i_el]
i_el+=1
out[i_bas] = tmp
return 0
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("accumulate", ["accumulate.pyx"], extra_compile_args=["-O3",])]
setup(
name = 'Accumulate',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
@zonca
Copy link
Author

zonca commented May 25, 2012

cython -a output for the last line (return 0):

24:     return 0
  /* "accumulate.pyx":24
 *             i_el+=1
 *         out[i_bas] = tmp
 *     return 0             # <<<<<<<<<<<<<<
 */
  __Pyx_XDECREF(__pyx_r);
  __Pyx_INCREF(__pyx_int_0);
  __pyx_r = __pyx_int_0;
  goto __pyx_L0;

  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  { PyObject *__pyx_type, *__pyx_value, *__pyx_tb;
    __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);
    __Pyx_SafeReleaseBuffer(&__pyx_bstruct_a);
    __Pyx_SafeReleaseBuffer(&__pyx_bstruct_section_lengths);
    __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out);
  __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}
  __Pyx_AddTraceback("accumulate.accumulate", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  goto __pyx_L2;
  __pyx_L0:;
  __Pyx_SafeReleaseBuffer(&__pyx_bstruct_a);
  __Pyx_SafeReleaseBuffer(&__pyx_bstruct_section_lengths);
  __Pyx_SafeReleaseBuffer(&__pyx_bstruct_out);
  __pyx_L2:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment