Skip to content

Commit 42432cf

Browse files
committed
A new exercise illustrating C-functions
1 parent 95eb47a commit 42432cf

File tree

5 files changed

+66
-0
lines changed

5 files changed

+66
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ courses are stored in tags.
4242
### Optimising with Cython
4343

4444
- [Creating simple extension](cython/simple-extension)
45+
- [Using C-functions](cython/c-functions)
4546
- [Optimising heat equation](cython/heat-equation)
4647

4748
### Interfacing with libraries

cython/c-functions/README.md

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
## Using C-functions
2+
3+
Fibonacci numbers are a sequence of integers defined by the recurrence
4+
relation
5+
6+
F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>
7+
8+
with the initial values F<sub>0</sub>=0, F<sub>1</sub>=1.
9+
10+
The module [fib.py](fib.py) contains a function `fibonacci(n)` that
11+
calculates recursively F<sub>n</sub>. The function can be used e.g. as
12+
13+
```python
14+
from fib import fibonacci
15+
16+
fibonacci(30)
17+
```
18+
19+
Make a Cython version of the module, and investigate how adding type
20+
information and making `fibonacci` a C-function affects performance
21+
(hint: function needs to be called both from Python and C). Use
22+
`timeit` for performance measurements, either from command line
23+
24+
```bash
25+
$ python3 -m timeit -s "from fib import fibonacci" "fibonacci(30)"
26+
```
27+
28+
or within IPython
29+
30+
```python
31+
In []: %timeit fibonacci(30)
32+
```
33+
34+
**Note:** this recursive algorithm is very inefficient way of calculating
35+
Fibonacci numbers and pure Python implemention of better algorithm
36+
outperforms Cython implementation drastically.

cython/c-functions/fib.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
def fibonacci(n):
2+
if n < 2:
3+
return n
4+
return fibonacci(n-2) + fibonacci(n-1)

cython/c-functions/solution/fib.pyx

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
cpdef int fibonacci(int n):
2+
if n < 2:
3+
return n
4+
return fibonacci(n-2) + fibonacci(n-1)
5+
6+
def fibonacci_py(int n):
7+
if n < 2:
8+
return n
9+
return fibonacci_py(n-2) + fibonacci_py(n-1)
10+
11+
def fibonacci_py2(n):
12+
if n < 2:
13+
return n
14+
return fibonacci_py2(n-2) + fibonacci_py2(n-1)

cython/c-functions/solution/setup.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from distutils.core import setup, Extension
2+
from Cython.Build import cythonize
3+
4+
ext = Extension("fib",
5+
sources=["fib.pyx"],
6+
)
7+
8+
setup(
9+
ext_modules=cythonize(ext)
10+
)
11+

0 commit comments

Comments
 (0)