#!/usr/local/bin/python
#
def t1(a):
t = 0
for i in range(100):
if a.has_key(i):
t = t + a[i]
return t
def t2(a):
t = 0
for i in range(100):
try:
t = t + a[i]
except:
pass
return t
def main():
print 3
a = {}
print 4
for i in range(10):
a[10 * i] = i
print 5
import profile
print 1
profile.run('print t1(a)')
print 2
profile.run('print t2(a)')
print 6
main()
Function t1 and t2 both add 1 + 2 + ... + 99 ( = 4950 ), using two
methods: a is a dictionary {10: 1, 2: 20, ..., 990: 99}. t1 uses
a.has_key() to see if a has the right key (success: 1/10), t2 uses
a try/except statement to do the same test.
Here are the result of this program on a Sparc 10/SunOS 4.1.3:
4950
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.017 0.017 0.100 0.100 <string>:0(?)
1 0.083 0.083 0.083 0.083 test.py:4(t1)
4950
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.033 1.033 1.033 1.033 test.py:11(t2)
1 0.000 0.000 1.033 1.033 <string>:0(?)
The function using try/except takes more than 10 times the function using
has_key.
Does it mean that we shouldn't use try/except statements except in a few
special cases ? For example, shouldn't we never use string.index but
string.find instead ? (string.find doesn't raise an exception)
Sam
-- "La cervelle des petits enfants, ca doit avoir comme un petit gout de noisette" Charles Baudelaire