[Q] Are Exceptions used that much in practice?

Alex Martelli aleaxit at yahoo.com
Tue Dec 19 09:00:57 EST 2000


"Aahz Maruch" <aahz at panix.com> wrote in message
news:91m1as$e9j$1 at panix2.panix.com...
> In article <Pine.GSO.4.21.0012122229470.19682-100000 at y.glue.umd.edu>,
> Roy Katz  <katz at Glue.umd.edu> wrote:
> >
> >If you enclose statements in a try/except clause, and assuming no
> >exception is thrown, what are the runtime penalties?
>
> Minimal, from what I've heard, but I don't feel like doing any
> benchmarking right now.

Depends on how much you're doing.  If the amount of
work is minimal, the overhead can easily get as big
as 10% or so...:

import time

def clean(n):
    tot = 0L
    for i in range(n):
        tot += i
    return tot

def safe(n):
    tot = 0L
    for i in range(n):
        try: tot += i
        except ValueError: pass
    return tot

start = time.clock()
tot = clean(100000)
stend = time.clock()
print 'clean:', stend-start

start = time.clock()
tot = safe(100000)
stend = time.clock()
print 'safe:', stend-start


D:\PySym>python ddd.py
clean: 0.650930034144
safe: 0.724842480024

D:\PySym>python ddd.py
clean: 0.645219254062
safe: 0.726402175024

D:\PySym>python ddd.py
clean: 0.651437081686
safe: 0.726812003533

D:\PySym>


So, putting a try/except around (say) each single
addition *does* have measurable impact.  A grain
a _tad_ less fine than this might be better, if
performance is an important issue.


Alex






More information about the Python-list mailing list