Alex Rivera | Logout

How much overhead do decorators add to Python function calls

Asked 2010-08-23T08:06:08.830
23

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.

Edit
Report

1 Answer

1

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

They add almost no measurable overhead. Zero.

It's important to note that the decorator runs once to create the decorated function. Once.

The decorated function has two parts to it.

  1. whatever decoration was added. This is not overhead.

  2. plus the original function. This is not overhead.

There's no real overhead at all. You might -- with some care -- be able to measure the overhead of one extra function call-and-return as part of a decorated function, but that's almost unmeasurably small. And it's probably far less than an alternative design that doesn't use decoration.

answered 2010-08-23T13:33:07.513

Your Answer