Two questions about efficiency

Peter Otten __peter__ at web.de
Fri May 28 04:44:31 EDT 2004


Steve M wrote:

> Peter Otten <__peter__ at web.de> wrote
> <snip>
>> Two results stand out: misses are cheap for DictIn and expensive for
>> DictTry.
> 
> That's very interesting, thanks so much Peter and the others.
> 
> So, contrary to your (and, incidentally, Wittgenstein's) admonition to
> look not think, why, would you speculate, is this the case? The
> overhead from creating an exception object?

Again, why would I speculate if I can measure?

try ... except:

$ timeit.py -s"key='a'" "try: raise KeyError('KeyError: %r' % key)" "except
KeyError: pass"
100000 loops, best of 3: 5.22 usec per loop

share of exception object creation:

$ timeit.py -s"key='a'" "KeyError('KeyError: %r' % key)"
100000 loops, best of 3: 2.96 usec per loop

So the exception mechanism accounts for more than 5 of 9 extra usec. You can
perhaps find out where the rest stems from if you dig deeper, but I'm too
lazy right now.
Which reminds me, timing with this simple tool is not only fun - I've found
my intuition proved wrong often enough, so it saves me from optimizing
portions of the code that are already fast.

Peter




More information about the Python-list mailing list