Python decorator for timing functions

While developing web applications for larger scale sometimes every milisecond makes great difference for end users. Except HTTP server caching, minifying your CSS and JS files, it is always good to take care about server-side functions executions (especially when they includes many database queries to run).

Today I would like to share with you some usefull Python decorator which will can bring for you some benefits in cutting loading time of you web sites.

import decorator

@decorator
def timing(func, *args, **kwargs):
    '''Function timing wrapper
        Example of using:
        ``@timing()``
    '''

    fn = '%s.%s' % (func.__module__, func.__name__)

    timer = Timer()
    with timer:
        ret = func(*args, **kwargs)

    log.info(u'%s - %0.3f sec' % (fn, timer.duration_in_seconds()))
    return ret

You can import it, and use as decorator befor your functions declaration, for example:

@timing

def your_fun():

    pass

I hope it will help your with performance tuning and future performance investigations.

Best regards,

MobilePro.pl