Wednesday, January 20, 2016

Timing django/python function calls

Doing some optimization for I've come across a handy snippet to time the execution of python/django functions. Since I was doing deep-dive checking I also wanted to know the stack of the executed function. Figured someone (me) would want to use it in the future, so I'm adding it here. Not the prettiest of code, but it works.

import time
import inspect                                                
def timeme(method):
    def time_wrapper(*args, **kw):
        startTime = int(round(time.time() * 1000))
        result = method(*args, **kw)
        endTime = int(round(time.time() * 1000))
        for i in inspect.stack():
            if i[3] == 'time_wrapper': continue 
        print 'Time(ms): ', ('%04d')%(endTime - startTime), method.__name__, u'->' ,u'->'.join(reversed(stack[0:5]))
        #only show 5 top stack
        return result
    return time_wrapper

#usage example
def some_function(x,y):
    return something