A Python Function Timing Decorator

I recently went up to North Carolina to visit a good friend of mine, and we got to talking Python as we are wont to do. He told me about a PEP for enhancing generator syntax and creating cofunctions. To get ready for these we needed to practice using coroutines. I went about this by enhancing my function timing decorator and making it into a class so I could collect and analyze timings on many different functions. Check out the gist, hopefully it will not make you think me a fool, I will discuss my thoughts on it below the code and remove all doubt.

I personally can’t get over how cool decorators are… but I digress. The key part is in the __collector function on line 11 where we collect data anytime a decorated function is called. So our dictionary of function names and timing information is being generated rather than simply populated. This allows us to lump together any special processing we want to do during the collection of a timing, such as adding to the count of timings or keeping a running total.
So this is cool because we can create a coroutine which is like building a generator, but cofunctions are cool because they allow you to essentially “go both ways,” meaning you can have a generator that generates values, but also receives values from another generator. Once you have this two way yielding communication you can do sweet stuff like a scheduler, which excites me because OpenCL is designed with an event driven interface, meaning one could setup a really slick OpenCL accelerated workflow using cofunctions with PyOpenCL.

2 thoughts on “A Python Function Timing Decorator

  1. Pingback: Rndm » Blog Archive » Python generators

Comments are closed.