Comparaison cython/python : méthode des rectangles

In [3]:
%load_ext cythonmagic
In [4]:
%%cython
cdef double cf(double x):    
   return x**2 - 2 * x

def cintegre(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s  = 0
    dx = (b - a) / N
    for i from 0 <= i < N:
        s += cf(a + i*dx)
    return s*dx
In [5]:
cintegre(0,2,2**20)
Out[5]:
-1.333333333336793
In [15]:
%timeit cintegre(0,2,2**20)
100 loops, best of 3: 4.76 ms per loop

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

def integre(a, b, N):
    s  = 0    
    dx = (b - a) / N
    for i in range(N):   
       s += f(a + i*dx)
    return s*dx
In [8]:
integre(0.,2.,2**20)
Out[8]:
-1.333333333336793
In [11]:
%timeit integre(0.,2.,2**20)
1 loops, best of 3: 417 ms per loop

In [10]:
417/4.76
Out[10]:
87.60504201680672
Python est 87 fois plus lent que cython sur cet exemple...
In [20]:
def f(x):    
   return x**2 - 2 * x

def integre2(a, b, N):
    dx = (b - a) / N
    return dx * sum([f(a + i*dx) for i in range(N)])
In [24]:
%timeit integre2(0.,2.,2**20)
1 loops, best of 3: 428 ms per loop

In [29]:
from functools import reduce

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

def integre3(a, b, N):
    dx = (b - a) / N
    return dx * reduce(lambda s,i : s + f(a + i*dx),range(N),0)
In [30]:
integre3(0.,2.,2**20)
Out[30]:
-1.333333333336793
In [31]:
%timeit integre3(0.,2.,2**20)
1 loops, best of 3: 509 ms per loop

In []: