Inline generator expressions with Cython

Besides any() and all(), Cython also has support for inline generator expressions in sum() now - and it’’s fast!

# CPython 2.6.5:
timeit "sum(i for i in xrange(10000))"
1000 loops, best of 3: 584 usec per loop
# Cython 0.13-pre:
def range_sum_typed(int N):
    cdef int result = sum(i for i in range(N))
    return result

timeit "range_sum_typed(10000)"
100000 loops, best of 3: 2 usec per loop

Obviously a really stupid benchmark, but still - that’’s what I call a difference!

Here’’s another benchmark for looping over a fixed list of Python integers instead:

# CPython 2.6.5:
timeit -s "r=range(10000)"  "sum((i*i for i in r), 100)"
1000 loops, best of 3: 868 usec per loop
# Cython 0.13-pre:
def typed_sum_squares(seq, int start):
    cdef long i, result
    result = sum((i*i for i in seq), start)
    return result

timeit -s "r=range(10000)"  "typed_sum_squares(r, 100)"
10000 loops, best of 3: 49.9 usec per loop

Not exactly what I”d call “closer”. ;)

Leave a Reply