undefined variable ?
Josiah Carlson
jcarlson at uci.edu
Sat Oct 16 11:58:01 EDT 2004
> Are exceptions cheap in Python then? Coming from Java, I know there's
> all sorts of overhead involved in creating and throwing an exception
> there...
They are not free, but they aren't that bad either...
>>> import time
>>> def te(n):
... for i in xrange(n):
... try:
... j = 1
... except:
... pass
...
>>> def tf(n):
... for i in xrange(n):
... try:
... raise #generally improper use
... except:
... pass
...
>>> def tf2(n):
... for i in xrange(n):
... try:
... j = l
... except:
... pass
...
>>> def ne(n):
... for i in xrange(n):
... j = 1
...
>>> t = time.time();te(1000000);time.time()-t
0.92100000381469727
>>> t = time.time();tf(1000000);time.time()-t
7.7030000686645508
>>> t = time.time();tf(1000000);time.time()-t
27.0
>>> t = time.time();ne(1000000);time.time()-t
0.57899999618530273
>>>
The no-exception version runs in ~.58 seconds, with-exception handling
(none raised) runs in ~.92 seconds, the first exception raiser runs in
~7.7 seconds, and the name error on assignment runs in ~27 seconds.
As long as you aren't relying on exception handling as a major part of
your algorithms, and are actually using them as /error handling/, I
wouldn't worry too much; the rest of us don't (we prefer properly
running scripts).
- Josiah
More information about the Python-list
mailing list