[sf-lug] [PyClass] code for a timeit decorator

jim jim at well.com
Wed Mar 11 07:48:57 PDT 2009

taken from 
which has some other interesting decorators as well. 

A very simple decorator to notify users (no profiling) about the
execution time of some parts of your code.

# comments below are mine (js) ; the idea of a decorator is that you 
# make a function and then use it in tandem with other functions 
# (or classes) in your code. note it makes little sense to make 
# a decorator if you don't use it with more than one function. 
# the point is that using a function as a decorator lets you 
# distribute some kind of behavior into multiple other functions 
# without duplicating the code within each of the other functions. 

--------------THE CODE--------------
import time
def timemeth(func):        # define a function, nothing special 
    "Internal class method timing decorator"
    def _inner(self, *args, **kw):
        start = time.time()
        res = func(self, *args, **kw)
        self.timed = time.time() - start
        return res
    return _inner
class TimedClass:
    def __init__(self):
        self.timed = 0
class Sample(TimedClass):
    @timemeth    # use the @ symbol with the function name... 
    def learn(self):   # ...immediately above whatever you want...  
        for i in range(1000000):   # ...to decorate... 
            i * i
if __name__ == "__main__": 
    s = Sample()
    print "Learning sample..."
    print "Learning done ! (%.2f secs)" % s.timed

--------------THE CODE--------------


$ python timedclass.py
Learning sample...
Learning done ! (2.01 secs)

More information about the sf-lug mailing list