Cost of raising exceptions.
Les Schaffer
schaffer at optonline.net
Tue May 29 14:19:55 EDT 2001
On Tue, 29 May 2001 17:29:24 +0200, "Alex Martelli" <aleaxit at yahoo.com>
wrote:
>So: if we're having an exception about one time in 20, the
>cost of the exceptions-in-loop approach is about 20%.
i had a similar question when i was doing lots of stats computations on
generic types.
i was curious how expensive it was to try/except vs. checking types.
so here's my little play script:
#!/usr/bin/python -O
# test whether exceptions or type testing take more time.
import time
x = 'NA'
xp = 1.000
y = 3.1415926
NMAX = 100000
def timeIt( func ):
start = time.time()
name = func()
end = time.time()
print '%s took %5.4f seconds'%(name, end - start)
def typeCheck():
for i in range(NMAX):
if i < CUTOFF:
X = x
else:
X = xp
if type(X) == type(y):
z = X*y
else:
pass
return 'typeCheck'
def tryExcept():
for i in range(NMAX):
if i < CUTOFF:
X = x
else:
X = xp
try:
z = X*y
except TypeError, e:
#print e
pass
return 'tryExcept'
for FRACTION_THAT_ARE_NA in [ 0, .2, .4, .6, .8, 1]:
print 'For fraction that are NA = %f:'%FRACTION_THAT_ARE_NA
CUTOFF = FRACTION_THAT_ARE_NA * NMAX
timeIt( typeCheck )
timeIt( tryExcept )
print
====== results ======
For fraction that are NA = 0.000000:
typeCheck took 0.4220 seconds
tryExcept took 0.2180 seconds
For fraction that are NA = 0.200000:
typeCheck took 0.4690 seconds
tryExcept took 0.6090 seconds
For fraction that are NA = 0.400000:
typeCheck took 0.4690 seconds
tryExcept took 0.9850 seconds
For fraction that are NA = 0.600000:
typeCheck took 0.4530 seconds
tryExcept took 1.3750 seconds
For fraction that are NA = 0.800000:
typeCheck took 0.4220 seconds
tryExcept took 1.7500 seconds
For fraction that are NA = 1.000000:
typeCheck took 0.3750 seconds
tryExcept took 2.0000 seconds
More information about the Python-list
mailing list