Search code examples
pythonperformancedecorator

How much overhead do decorators add to Python function calls


I've been playing around with a timing decorator for my pylons app to provide on the fly timing info for specific functions. I've done this by creating a decorator & simply attaching it to any function in the controller I want timed.

It's been pointed out however that decorators could add a fair amount of overhead to the call, and that they run 2-3x slower than an undecorated function.

Firstly, I would expect that executing a decorated function would take a smite longer than an undecorated one, but I would expect that overhead to be in the thousandths of seconds & be negligible compared to a SQL insert call. The decorator itself does simple simple timing calculations using time.time() & some very simple aggregation.

Do decorators add significant overhead to a system? I can't find anything to back that up.


Solution

  • The overhead added by using a decorator should be just one extra function call.

    The work being done by the decorator isn't part of the overhead as your alternative is to add the equivalent code to the decorated object.

    So it's possible that the decorate function takes twice as long to run, but that's because the decorator is doing some important work that takes roughly the same time to fun as the undecorated function.