[sf-lug] [PyClass] code for a timeit decorator
jim at well.com
Wed Mar 11 07:48:57 PDT 2009
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.
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
self.timed = 0
@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
$ python timedclass.py
Learning done ! (2.01 secs)
More information about the sf-lug