[wiki: Profilage]
#!comment
https://www.cognitoforms.com/COMSOFT1/IntelAcc%C3%A9l%C3%A9rezVotreCodePythonOct16
METTRE A JOUR A PARTIR DE LA PRESENTATION PYTHRAN DE LOIC : http://python-scientific-lecture-notes.developpez.com/tutoriels/note-cours/apprendre-python-optimisation-code/
VERIFIER AUSSI : http://python-scientific-lecture-notes.developpez.com/tutoriels/note-cours/apprendre-python-optimisation-code/
http://pypy.org/ (sandbox, stackless execution)
fibo.py :
#!python
def fib(n):
# from http://en.literateprograms.org/Fibonacci_numbers_(Python)
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def fib_seq(n):
seq = [ ]
if n > 0:
seq.extend(fib_seq(n-1))
seq.append(fib(n))
return seq
Module timeit
Ce module permet de répéter un certain nombre de fois une instruction donnée, au sein d’un environnement virtuel isolé, et de mesurer son temps d’éxécution :
>>> import timeit
>>> t = timeit.Timer("print fib_seq(20); print","import fibo") 1
>>> t.timeit()
8.21683733547
>>> t.repeat(3, 2000000)
[16.48319309109, 16.46128984923, 16.44203948912]
Modules profile, cProfile et pstats
Le module profile permet d’obtenir des statistiques sur le temps passé dans les différentes fonctions :
#!python
>>> import profile
>>> import fibo
>>> profile.run('print fib_seq(20); print')
Le module cProfile est une variante optimisée, à utiliser en priorité lorsqu’elle est disponible pour votre configuration.
On peut utiliser pstats pour faire des statistiques d’exécution et améliorer la mise en page et les informations affichées :
#!python
import profile
import pstats
import fibo
# Create 5 set of stats
filenames = []
for i in range(5):
filename = 'profile_stats_%d.stats' % i
profile.run('print %d, fib_seq(20)' % i, filename)
# Read all 5 stats files into a single object
stats = pstats.Stats('profile_stats_0.stats')
for i in range(1, 5):
stats.add('profile_stats_%d.stats' % i)
# Clean up filenames for the report
stats.strip_dirs()
# Sort the statistics by the cumulative time spent in the function
stats.sort_stats('cumulative')
# limit output to lines with "(fib" in them
stats.print_stats('\(fib')
Gprof2Dot
Références
- Python module of the week
- The Python profilers
- [http://mybinder.org/repo/gouarin/loops_pythran/notebooks/loops_pythran.ipynb]