Should I use "if" or "try" (as a matter of speed)?

Terry Reedy tjreedy at udel.edu
Sat Jul 9 16:31:31 EDT 2005


"wittempj at hotmail.com" <martin.witte at gmail.com> wrote in message 
news:1120935497.365395.168900 at g47g2000cwa.googlegroups.com...
> My shot would be to test it like this on your platform like this:
>
> #!/usr/bin/env python
> import datetime, time
> t1 = datetime.datetime.now()
> for i in [str(x) for x in range(100)]:
> if int(i) == i:
> i + 1
> t2 = datetime.datetime.now()
> print t2 - t1
> for i in [str(x) for x in range(100)]:
> try:
> int(i) +1
> except:
> pass
> t3 = datetime.datetime.now()
> print t3 - t2

This is not a proper test since the if condition always fails and the 
addition not done while the try succeeds and the addition is done.  To be 
equivalent, remove the int call in the try part: try: i+1.  This would 
still not a proper test since catching exceptions is known to be expensive 
and try: except is meant for catching *exceptional* conditions, not 
always-bad conditions.  Here is a test that I think more useful:

for n in [1,2,3,4,5,10,20,50,100]:
  # time this
  for i in range(n):
    if i != 0: x = 1/i
    else: pass
  # versus
  for i in range(n):
    try x = 1/i
    except ZeroDivisionError: pass

I expect this will show if faster for small n and try for large n.

Terry J. Reedy






More information about the Python-list mailing list