Mauro Baraldi - Python Brasil 2012
Como medir a sua aplicação
Introdução à conceitos de profiling, debug e tracing
Quem sou eu?
http://www.66batman.com/cgi-bin/yabb2/YaBB.pl?num=1296085129
Mauro Navarro Baraldi
Desenvolvedor
Mais
Programando em Python desde 2001
Pai da Maria Eduarda,
do João Fernando
e marido da Camila
Tópicos - Conceitos - Por que monitorar uma aplicação - Debugging - Profiling - Tracing - Memory Profiling - Holly Grail - Dúvidas?
Conceitos- Debug: Metodo de Investigação do sistema (em execução) em busca do problema/erro.
- Profiling: Análise dinâmica de um sistema para medir recursos usado por ele no sistema.
- Tracing: Processo de gravar o comportamento de runtime do sistema para análise (debug/profiling)
Porque monitorar uma aplicação - Aprendizado
- Bugs
- Segurança
- Desempenho
Premature optimization is the root of all evil.
Tony Hoare
http://www.turing100.manchester.ac.uk/index.php/speakers/invited-list/11-speakers/39
Debugginghttp://static.ddmcdn.com/gif/myths-everyday-science-1.jpg
pdbBiblioteca da padrão para debugging de código
Prós: - fácil - simples - nativa
Contras: - IMHO nenhum!
debug_app.py#!/usr/bin/env python
from pdb import set_trace
def debug_me(value): set_trace() # Aqui ativa-se o debug
if value > 0: print 'positivo' elif value < 0: print 'negativo' else: print 'zero'
if __name__ == '__main__': debug_me(0)
resultado do pdbmauro@r2d2:~/projetos/pythonbrasil8$ python pdb_app.py > /home/mauro/projetos/pythonbrasil8/pdb_app.py(9)debug_me()-> if value > 0:(Pdb) n> /home/mauro/projetos/pythonbrasil8/pdb_app.py(11)debug_me()-> elif value < 0:(Pdb) n> /home/mauro/projetos/pythonbrasil8/pdb_app.py(14)debug_me()-> return 'zero'(Pdb) n--Return--> /home/mauro/projetos/pythonbrasil8/pdb_app.py(14)debug_me()->'zero'-> return 'zero'(Pdb) n--Return--> /home/mauro/projetos/pythonbrasil8/pdb_app.py(17)<module>()->None-> debug_me(0)(Pdb) n
Profiling
http://www.guardian.co.uk/books/booksblog/2012/oct/30/scary-stories-halloween-francis-marion-crawford
Standard Library
http://aidsource.ning.com/page/resource-library
cProfileBiblioteca padrão para profiling
Prós: - standard lib - baixo impacto na execução. - usa extensão em C Contras: - só funciona com metodos - não há suporte para gráficos (nativo)
profile_app.py#!/usr/bin/env python
def profile_me(limit):
counter = 0
while counter <= limit: counter = counter + 1
if __name__ == '__main__': profile_me(10)
resultado do profilemauro@r2d2:~/projetos/pythonbrasil8$ python -m cProfile profile_app.py 1 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
8 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 cProfile.py:132(run) 1 0.000 0.000 0.001 0.001 cProfile.py:137(runctx) 1 0.000 0.000 0.001 0.001 cProfile.py:14(run) 1 0.000 0.000 0.000 0.000 cProfile.py:5(<module>) 1 0.000 0.000 0.000 0.000 cProfile.py:66(Profile) 1 0.000 0.000 0.001 0.001 profile_app.py:3(<module>) 1 0.000 0.000 0.000 0.000 profile_app.py:5(profile_me) 1 0.001 0.001 0.001 0.001 {method 'enable' of '_lsprof.Profiler' objects
resultado do profile - legendancalls: numero de chamados
tottime: tempo total gasto na função dada (excluindo o tempo feito nas chamadas para sub-funções)
percall: tottime/ncalls
cumtime: tempo total gasto nesta e todas as subrotinas
percall: cumtime/ncalls
filename:lineno(function): dados respectivos de cada função
profileOutra biblioteca inspirada na cProfile (Pure Python)
Prós: - standard lib Contras: - os mesmo da cProfile - impacto significante na execução.
Usada para extender as funcionalidades do profiler default (cProfile).
hotshotBiblioteca para profiling em alto desempenho
Prós: - standard lib - baixo impacto na execução, cProfile.
Contras: - mais lento na geração dos dados - não funciona bem com threads - será descontinuado em breve.
Bibliotecas e Aplicações Externas
line_profilerProfiling linha a linha
Prós: - simples e fácil - usa a cProfile - visão detalhada da execução do código.
Contras: - desempenho inferior ao cProfile - resultado resumido
resultado do line_profilermauro@r2d2:~/projetos/pythonbrasil8$ kernprof.py -l line_profile_app.pyWrote profile results to line_profile_app.py.lprof
mauro@r2d2:~/projetos/pythonbrasil8$ python -m line_profiler line_profile_app.py.lprof Timer unit: 1e-06 s
File: line_profile_app.pyFunction: profile_me at line 3Total time: 1e-05 s
Line # Hits Time Per Hit % Time Line Contents============================================================== 3 @profile 4 def profile_me(limit): 5 6 1 1 1.0 10.0 counter = 0 7 8 12 5 0.4 50.0 while counter <= limit: 9 11 4 0.4 40.0 counter = counter + 1
Análisehttp://blog.hubspot.com/blog/tabid/6307/bid/31619/How-to-Conduct-Competitive-Analysis-to-Step-Up-Your-Content-Strategy.aspx
RunSnakeRunAnalise de dados gerados a partir do profiler.
http://mg.pov.lt/run-snake-run.png
$ python -m cProfile -o snake.data runsnakerun_app.py
runsnakerun_app.py
gerando os dados de análise
#!/usr/bin/env python
def print_function(data): print data
def char2ord(char): return ord(char)
def profile_me(word):
for char in word: num = char2ord(char) print_function('Ordinal from %s is %i' % (char, num))
if __name__ == '__main__': profile_me("Python Brasil 8")
visualização da análise
http://cavemanreflections.blogspot.com.br/p/follow-yellow-brick-road.html
Tracing
traceBiblioteca da padrão para tracing de código
Prós: - fácil - simples - nativa
Contras: - IMHO nenhum!
trace_app.py#!/usr/bin/env python
def trace_me(value):
if value > 0: return 'positivo' elif value < 0: return 'negativo' else: return 'zero'
if __name__ == '__main__': trace_me(0)
resultado do line_profiler$ python -m trace --trace trace_app.py --- modulename: trace_app, funcname: <module>trace_app.py(3): def trace_me(value):trace_app.py(12): if __name__ == '__main__':trace_app.py(13): trace_me(0) --- modulename: trace_app, funcname: trace_metrace_app.py(5): if value > 0:trace_app.py(7): elif value < 0:trace_app.py(10): return 'zero' --- modulename: trace, funcname: _unsettracetrace.py(80): sys.settrace(None)
disptraceTracing de código exportando a saida para HTML
Prós: - exporta em um formato visual
Contras: - roda dentro de um contexto da app
disptrace_app.pyimport disptrace
def browse_disptrace(dt): import tempfile, webbrowser, urllib, os
html = dt.render() tempfiledes, temppath = tempfile.mkstemp(suffix='.html') tempfile = os.fdopen(tempfiledes, "w") tempfile.write(html) tempfile.close() tempurl = "file://{}".format(urllib.pathname2url(temppath)) webbrowser.get(None).open_new(tempurl)
def if_test(a, b, c): if a > 10: print "this" elif b > 10: print "that" else: print "result is", b*c
t = disptrace.DispTrace()t.runfunc(if_test, 1, 2, 3)browse_disptrace(t)
visualização da análise
http://spectrum.ieee.org/semiconductors/memory/the-quest-for-a-universal-memory
Memory Profiling
memory profilerProfiling de memoria
Prós: - facil - simples - integração com pdb
Contras: - Não encontrei
memory_profiler_app.py@profiledef potencia(expoente): for i in range(expoente): print '2^%i = %i' % (i, pow(2,i))
if __name__ == '__main__': potencia(10)
resultado do memory_profiler$ python -m memory_profiler memory_profile_app.pyFilename: memory_profile_app.py
Line # Mem usage Increment Line Contents================================================ 3 @profile 4 9.00 MB 0.00 MB def potencia(expoente): 5 9.00 MB 0.00 MB for i in range(expoente): 6 print '2^%i = %i' % (i, pow(2,i))
http://janeaustenfilmclub.blogspot.com.br/2011/06/monty-python-and-holy-grail.html
All together
http://www.shopping.com/Toy-Vault-Monty-Python-s-Holy-Grail-Plush/info
Holly Grail
psutilsbiblioteca de monitoramento de recursos do sistema
Prós: - multi-plataforma - fácil - resultados em estruturas de dados Python - monitora: - cpu/processos - memoria/discos, - rede - usuarios
ReferenciasMódulos e aplicaçõespdb: http://docs.python.org/2/library/pdb.html
cProfile: http://docs.python.org/2/library/profile.html
line_profiler: http://packages.python.org/line_profiler/
RunSnakeRun: http://www.vrplumber.com/programming/runsnakerun/
trace: http://docs.python.org/2/library/trace.html
disp_trace: https://github.com/atsuoishimoto/disptrace
memory_profiler: https://github.com/fabianp/memory_profiler
psutil: http://code.google.com/p/psutil/
MaisCode Profiling: http://en.wikipedia.org/wiki/Code_profiling
Python Profiling: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code
Profile Hooks (decorators for Python profiling): http://mg.pov.lt/profilehooks/
http://fogsmoviereviews.com/2012/06/24/movies-that-everyone-should-see-monty-python-and-the-holy-grail/
Dúvidas?
Source Codehttps://github.com/maurobaraldi/pybr8
http://spectrumculture.com/2010/01/film-dunce-monty-python-and-the-holy-grail.html/
Thank You