Feeds:
Posts
Comments

Este es mi primer post de una serie sobre rendimiento en python y cómo alcanzarla. Mi primer post trata sobre variables globales. No recomiendo el uso de estas variables excepto en contados casos, las razones son múltiples, pero en caso que tengas que usarlas, ten en cuenta este pequeño test:

from profileit import profileit

globalVar = 0
cycles = 1000000

@profileit(0)
def globalTest ():
	global globalVar
	for i in range (cycles):
		globalVar += 1

# Local instead global search
@profileit(0)
def localTest ():
	global globalVar
	localVar = globalVar
	for i in range (cycles):
		localVar += 1
	globalVar = localVar

if __name__ == '__main__':
	globalTest ()
	localTest ()

Continue Reading »

This is my first post of a list about python performance and how to achieve it. My first post is about global variables. I don’t advise global variables except in few cases, reasons are multiples, but in case you have to use them, take into account this little test:

from profileit import profileit

globalVar = 0
cycles = 1000000

@profileit(0)
def globalTest ():
	global globalVar
	for i in range (cycles):
		globalVar += 1

# Local instead global search
@profileit(0)
def localTest ():
	global globalVar
	localVar = globalVar
	for i in range (cycles):
		localVar += 1
	globalVar = localVar

if __name__ == '__main__':
	globalTest ()
	localTest ()

Continue Reading »

Decoradores

Tengo que reconocer que descubrí está útil característica de python hace poco. Pero desde entonces le he encontrado un montón de usos. Estoy hablando sobre decoradores. Un decorador es una función que trabaja sobre otra función (o mejor dicho, alrededor de ella). Vamos a empezar fuerte, quiero enseñarte un decorador que verás más veces en estos posts, el decorador de profiling:

def profileit(printlines=1):
    def _my(func):
        def _func(*args, **kargs):
            prof = hotshot.Profile("profiling.data")
            res = prof.runcall(func, *args, **kargs)
            prof.close()
            stats = hotshot.stats.load("profiling.data")
            stats.strip_dirs()
            stats.sort_stats('time', 'calls')
            print '\n*** %s' % str (func)
            print ">>>---- Begin profiling print"
            stats.print_stats(printlines)
            print ">>>---- End profiling print"
            return res
        return _func
    return _my

Continue Reading »

Decorators

I’ve to recognize that I discovered this useful feature of python recently. But since that, I’ve found a lot of uses. I’m talking about decorators. A decorator is a function that works over another function (or around it). To start strongly, I want to show you a snippet that you will see more times in these posts, the profiling decorator:

def profileit(printlines=1):
    def _my(func):
        def _func(*args, **kargs):
            prof = hotshot.Profile("profiling.data")
            res = prof.runcall(func, *args, **kargs)
            prof.close()
            stats = hotshot.stats.load("profiling.data")
            stats.strip_dirs()
            stats.sort_stats('time', 'calls')
            print '\n*** %s' % str (func)
            print ">>>---- Begin profiling print"
            stats.print_stats(printlines)
            print ">>>---- End profiling print"
            return res
        return _func
    return _my

Continue Reading »

Módulo logging

Como desarrollador sobre python, en tus scripts debes proporcionar información tanto al usuario como a ti mismo. Estoy seguro que estás pensando en la mandato print, pero esto no es muy recomendable. Hoy quiero mostrarte por qué y darte algunos trucos sobre el módulo logging de python. Este módulo está especializado en loguear (obviamente), pero quizás no conozcas otras bondades que concede:

  • Logging en niveles: Puedes loguear en diferentes niveles y después filtrar la salida.
  • Logging múltiple: Puedes loguear la misma información sobre diferentes salidas (fichero, streams, …).
  • Logging jerárquico: Puedes definir una jerarquía de loggers para utilizar en tus scripts.

Continue Reading »

Logging module

As a python developer, in your scripts, you must provide information for the user and for yours. I’m sure you’re thinking on print statement, but this isn’t recommended. Today, I want to show why and give you some good tips about logging python module. This module is intended for logging (obviously), but maybe you dont know that this module provides:

  • Level logging: You can log in different level, filter outputs.
  • Multi logging: You can log into a file and stdout at the same time.
  • Hierarchical logging: You can define a hierarchical model of loggers.

Continue Reading »

« Newer Posts