Python timing decorator
Tuesday, January 27th, 2009I have been using python as my main scripting language for some time, but recently I wanted to profile some of my scripts to see why it was taking so long.
I looked at the python profiler but I keep looking for some reason.
Finally I found this code snippet (I don’t remember from where, maybe here one night at mccool s online )
You can use python @ decorator to wrap functions with timing metrics.
def print_timing(func): def wrapper(*arg): t1 = time.time() res = func(*arg) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return res return wrapper
Then simply use like this
@print_timing def some_func(n): //do work
This allows lots of control as you can put metrics on 1 or more functions.