File tree 5 files changed +66
-0
lines changed
5 files changed +66
-0
lines changed Original file line number Diff line number Diff line change @@ -42,6 +42,7 @@ courses are stored in tags.
42
42
### Optimising with Cython
43
43
44
44
- [ Creating simple extension] ( cython/simple-extension )
45
+ - [ Using C-functions] ( cython/c-functions )
45
46
- [ Optimising heat equation] ( cython/heat-equation )
46
47
47
48
### Interfacing with libraries
Original file line number Diff line number Diff line change
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.
Original file line number Diff line number Diff line change
1
+ def fibonacci (n ):
2
+ if n < 2 :
3
+ return n
4
+ return fibonacci (n - 2 ) + fibonacci (n - 1 )
Original file line number Diff line number Diff line change
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 )
Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments