Huard cythone
system:sage

<p>Un premier exemple. Nous utilisons le code de Benoit Huard pour resoudre le probleme 2 du projet Euler. Nous verrons comment cython aide a ameliorer la rapidite du code. (Notez que l'absence des accents ici est du a mon clavier et non au notebook de sage!)</p>

{{{id=0|
def Fibo(n):
	if n==0:
		return 1
	elif n==1:
		return 1
	else:
		return Fibo(n-1)+Fibo(n-2)


def Probleme2(jusqua=4000000):
	i=0
	Fib=Fibo(i)
	M=[]
	while Fib<=jusqua:
		if Fib%2==0:
			M.append(Fib)
		i+=1
		Fib=Fibo(i)
	print M
	print 'The sum is'
	return sum(M)
///
}}}

{{{id=1|
time Probleme2(4000000)
///


[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
The sum is
4613732
Time: CPU 25.13 s, Wall: 25.96 s
}}}

{{{id=15|
%cython
def Fibo_en_mieux(n):
	if n==0:
		return 1
	elif n==1:
		return 1
	else:
		return Fibo_en_mieux(n-1)+Fibo_en_mieux(n-2)


def Probleme2_en_mieux(jusqua=4000000):
	i=0
	Fib=Fibo_en_mieux(i)
	M=[]
	while Fib<=jusqua:
		if Fib%2==0:
			M.append(Fib)
		i+=1
		Fib=Fibo_en_mieux(i)
	print M
	print 'The sum is'
	return sum(M)
///
}}}

{{{id=13|
time Probleme2_en_mieux(4000000)
///


[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
The sum is
4613732
Time: CPU 6.05 s, Wall: 6.09 s
}}}

<p>Un autre exemple.</p>

{{{id=3|
def masomme(n):
    s = 0
    for i in range(n+1):
        s = s+i
    return s
///
}}}

{{{id=4|
time masomme(1000000)
///


500000500000
Time: CPU 2.01 s, Wall: 2.09 s
}}}

{{{id=8|
%cython
def masomme2(n):
    s = 0
    for i in range(n+1):
        s = s+i
    return s
///
}}}

{{{id=7|
time masomme2(1000000)
///


500000500000
Time: CPU 0.10 s, Wall: 0.11 s
}}}

{{{id=6|
%cython
def masomme3(int n):
    cdef int i
    cdef long long s
    s = 0
    for i in range(n+1):
        s = s+i
    return s
///
}}}

{{{id=5|
time masomme3(1000000)
///


500000500000L
Time: CPU 0.00 s, Wall: 0.00 s
}}}

{{{id=9|
timeit('masomme3(1000000)')
///


625 loops, best of 3: 1.26 ms per loop
}}}

{{{id=10|
timeit('masomme(1000000)')
///


5 loops, best of 3: 1.98 s per loop
}}}

{{{id=11|
1.98/0.00126
///


1571.42857142857
}}}

{{{id=12|

///
}}}