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

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Jul 9 16:39:20 EDT 2005


wittempj at hotmail.com a écrit :
> My shot would be to test it like this on your platform like this:
>  
> #!/usr/bin/env python
> import datetime, time

Why not use the timeit module instead ?

> t1 = datetime.datetime.now()
> for i in [str(x) for x in range(100)]:

A bigger range (at least 10/100x more) would probably be better...

> 	if int(i) == i:

This will never be true, so next line...

> 		i + 1

...wont never be executed.

> t2 = datetime.datetime.now()
> print t2 - t1
> for i in [str(x) for x in range(100)]:
> 	try:
> 		int(i) +1
> 	except:
> 		pass

This will never raise, so the addition will always be executed (it never 
will be in the previous loop).

> t3 = datetime.datetime.now()
> print t3 - t2

BTW, you  end up including the time spent printing t2 - t1 in the 
timing, and IO can be (very) costly.

(snip meaningless results)

The "test-before vs try-expect strategy" is almost a FAQ, and the usual 
answer is that it depends on the hit/misses ratio. If the (expected) 
ratio is high, try-except is better. If it's low, test-before is better.

HTH



More information about the Python-list mailing list