In [1]:
%%file fib.h

double fib(int n);
Overwriting fib.h
In [2]:
%%file fib.c

double fib(int n) {
    double a = 0, b = 1;
    for (int i=0; i<n; i++) {
        double tmp = b;
        b = a;
        a += tmp;
     }
    return a;
}
Overwriting fib.c
In [3]:
%%file fib.pxd

cdef extern from "fib.h":
    double fib(int n)
Overwriting fib.pxd
In [4]:
%%file fib2.pyx

cimport fib

def fib(n):
    return fib.fib(n)
Overwriting fib2.pyx
In [5]:
%%file setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize

ext = Extension("fib2",
              sources=["fib2.pyx", "fib.c"])

setup(name = "cython_fib",
      ext_modules = cythonize(ext))
Overwriting setup.py
In [6]:
! python3 setup.py build_ext -i
Compiling fib2.pyx because it changed.
[1/1] Cythonizing fib2.pyx
running build_ext
building 'fib2' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c fib2.c -o build/temp.linux-x86_64-3.5/fib2.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c fib.c -o build/temp.linux-x86_64-3.5/fib.o
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/fib2.o build/temp.linux-x86_64-3.5/fib.o -o /home/della/Documents/unicatt/courses/scientific_python/workspace/pycharm/notebooks/fib2.cpython-35m-x86_64-linux-gnu.so
In [7]:
from fib2 import fib
In [8]:
fib(100)
Out[8]:
3.54224848179262e+20
In [9]:
%timeit fib(100)
134 ns ± 2.42 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)