In [1]:
%load_ext Cython
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
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
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
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
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)
In [11]:
%timeit -n3 -r5 intg_c1(0, 10, 1000000)
In [12]:
%timeit -n3 -r5 intg_c2(0, 10, 1000000)
In [13]:
%timeit -n3 -r5 intg_c3(0, 10, 1000000)
In [15]:
%timeit -n3 -r5 intg_c4(0, 10, 1000000)