Skip to content

Fix julialang.org fib example for Cython #21

@eteq

Description

@eteq

Right now, the fibbonachi example (visible at http://nbviewer.ipython.org/url/refreweb.phys.ethz.ch/hope/notebooks/julialang.org.ipynb ... for some reason this doesn't match this repository?) reads:

cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
def cython_fib(int n):
    if n<2:
        return n
    return cython_fib(n-1)+cython_fib(n-2)

This is a mis-use of Cython, however. If you change it instead to

cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
cpdef int cython_fib(int n):
    if n<2:
        return n
    return cython_fib(n-1)+cython_fib(n-2)

That yields a drastic speedup, making the Cython example equivalent to native code (and hope).

The point is that using "def" in tight loops is a mis-use of Cython: it makes Cython functions act just like regular Python functions, rather than using it as a c function with an int return type, which is what makes the recursion here go fast.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions