Skip main navigation

Hands-on: Using C-functions

In this exercise you can practice using C-functions in Cython modules.
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
relation

Fn = Fn-1 + Fn-2

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

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

from fib import fibonacci

fibonacci(30)

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

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now