[Numpy-discussion] Right way of looping throught ndarrays using Cython

Lisandro Dalcin dalcinl at gmail.com
Fri Jun 20 17:26:40 EDT 2008


On 6/20/08, Gael Varoquaux <gael.varoquaux at normalesup.org> wrote:
>  I am trying to figure the right way of looping throught ndarrays using
>  Cython, currently. Things seem to have evolved a bit compared to what
>  some documents on the web claim (eg "for i from 0<=i<n" does not seem
>  faster than "for i in range(n)").

Regarding for loops, Cython recently gained an optimization (perhaps
you already know this, but just in case). If the 'i' variable is a
'cdef'  one, then Cython does not actually use 'range', but a plain C
for loop.  See yourself:

cdef void foo():
    cdef int i, j=0
    for i in range(5,20,3):
        j += i

The generated C code is (comments stripped):

static  void __pyx_f_7fortest_foo(void) {
  int __pyx_v_i;
  int __pyx_v_j;
  __pyx_v_j = 0;
  for (__pyx_v_i = 5; __pyx_v_i < 20; __pyx_v_i+=3) {
    __pyx_v_j += __pyx_v_i;
  }
}


Really, really nice!!!, doesn't it? You can just forget about the 'for
i from ...' form (at least for the 99% of the cases, I think).

Additionally, 'for' loops can now also be written like this (without 'from'):

for 0<= i < n:
    do_stuff()

but IMHO, the 'range' optimization is just a big win!

-- 
Lisandro Dalcín
---------------
Centro Internacional de Métodos Computacionales en Ingeniería (CIMEC)
Instituto de Desarrollo Tecnológico para la Industria Química (INTEC)
Consejo Nacional de Investigaciones Científicas y Técnicas (CONICET)
PTLC - Güemes 3450, (3000) Santa Fe, Argentina
Tel/Fax: +54-(0)342-451.1594



More information about the NumPy-Discussion mailing list