In [1]:
%load_ext Cython

Python version


In [2]:
def f_py(x):
    return x**2 -x

def intg_py(a, b, N):
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f_py(a + i*dx)
    return s * dx

Cython ver.1 same as .py


In [3]:
%%cython

def f_c1(x):
    return x**2 -x

def intg_c1(a, b, N):
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f_c1(a + i*dx)
    return s * dx

Cython ver.2 static typing


In [4]:
%%cython

def f_c2(double x):
    return x**2 - x

def intg_c2(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f_c2(a + i*dx)
    return s * dx

Cython ver.3 typing functions


In [5]:
%%cython

cdef double f_c3(double x) except? -2:
    return x**2 - x

def intg_c3(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f_c3(a + i*dx)
    return s * dx

Cython ver.4 typing functions (cpdef)


In [14]:
%%cython

cpdef double f_c4(double x) except? -2:
    return x**2 - x

def intg_c4(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f_c4(a + i*dx)
    return s * dx

In [10]:
%timeit -n3 -r5 intg_py(0, 10, 1000000)


317 ms ± 7.71 ms per loop (mean ± std. dev. of 5 runs, 3 loops each)

In [11]:
%timeit -n3 -r5 intg_c1(0, 10, 1000000)


203 ms ± 8.26 ms per loop (mean ± std. dev. of 5 runs, 3 loops each)

In [12]:
%timeit -n3 -r5 intg_c2(0, 10, 1000000)


63.3 ms ± 2.76 ms per loop (mean ± std. dev. of 5 runs, 3 loops each)

In [13]:
%timeit -n3 -r5 intg_c3(0, 10, 1000000)


1.87 ms ± 102 µs per loop (mean ± std. dev. of 5 runs, 3 loops each)

In [15]:
%timeit -n3 -r5 intg_c4(0, 10, 1000000)


2.1 ms ± 91.5 µs per loop (mean ± std. dev. of 5 runs, 3 loops each)