Skip main navigation

Hands-on: Using C-functions

In this exercise you can practice using C-functions in Cython modules.
© CC-BY-NC-SA 4.0 by CSC - IT Center for Science

In this exercise you can practice using C-functions in Cython modules.

The code for this exercise is located under cython/c-functions.

Fibonacci numbers are a sequence of integers defined by the recurrence

Fn = Fn-1 + Fn-2

with the initial values F0=0, F1=1.

The module contains a function fibonacci(n) that
calculates recursively Fn. The function can be used e.g. as

from fib import fibonacci


Make a Cython version of the module, and investigate how adding type
information and making fibonacci a C-function affects performance
(hint: function needs to be called both from Python and C). Use
timeit for performance measurements, either from command line

$ python3 -m timeit -s "from fib import fibonacci" "fibonacci(30)"

or within IPython

In []: %timeit fibonacci(30)

Note: this recursive algorithm is very inefficient way of calculating Fibonacci numbers.

How much speedup are you are able to get by using Cython? Are you able to come up with more efficient pure Python algortihm? Please comment!

© CC-BY-NC-SA 4.0 by CSC - IT Center for Science
This article is from the free online

Python in High Performance Computing

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education