Two questions about efficiency

Slawomir Nowaczyk slawek at cs.lth.se
Wed May 26 19:10:03 EDT 2004


On 26 May 2004 13:39:30 -0700
humean at fea.st (Steve M) wrote:

#> I am interested in his claim that the second version is less
#> efficient unless the requested key is "almost never" in the
#> dictionary. I would have thought that the overhead to do a key
#> lookup is quite a bit less than the overhead required to create an
#> exception object, so that the first version would be on average
#> more efficient only if the requested key is in the dictionary, say,
#> more than half the time.

#> Does the "key in dict" test internally raise an exception on
#> failure, thus incurring at least the same overhead as the first
#> version? Or is the overhead to raise an exception much less than I
#> have naively supposed?

#> I have a similar idiom buried in a nested loop, and I'd like to
#> select the approach that is likely to be most efficient. My best
#> guess is that the key lookup will fail half the time.

I suggest:

>>> import profile
>>> p = profile.profiler()
>>> def ver1():
...    # put version 1 here
...
>>> def ver2():
...    # put version 2 here
...
>>> p.run("ver1()").print_stats()
>>> p.run("ver2()").print_stats()

Do not forget to share the results :D

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

The Main Library at Indiana University sinks over an inch every
year because when it was built, engineers failed to take into
account the weight of all the books that would occupy the building.





More information about the Python-list mailing list