Getting started with python
James Stroud
jstroud at mbi.ucla.edu
Tue Apr 17 03:16:00 EDT 2007
Steve Holden wrote:
> James Stroud wrote:
>> Steve Holden wrote:
>>> You'd be worth more if you'd used elif and omitted the continue
>>> statements, but for a first solution it's acceptable.
>>
>> Depends on what you are after.
>>
>> py> s = """
>> ... for i in xrange(1,101):
>> ... if not i % 15:
>> ... continue
>> ... if not i % 5:
>> ... continue
>> ... if not i % 3:
>> ... continue
>> ... else:
>> ... pass
>> ... """
>> py> t = timeit.Timer(stmt=s)
>> py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>> 40.49 usec/pass
>> py> s = """
>> ... for i in xrange(1,101):
>> ... if not i % 15:
>> ... pass
>> ... elif not i % 5:
>> ... pass
>> ... elif not i % 3:
>> ... pass
>> ... else:
>> ... pass
>> ... """
>> py> t = timeit.Timer(stmt=s)
>> py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
>> 40.88 usec/pass
>>
>
> To be strictly comparable you should have pass statements before the
> continue statements as well. Ignoring that, clearly it's well worth
> saving that extra 390 nanoseconds each time round the loop.
>
> Repeat after me "premature optimization is the root of all evil".
>
> http://en.wikipedia.org/wiki/Optimization_(computer_science)
>
> regards
> Steve
The point is that both work equally as well unless (1) you are biased by
a particular style or (2) you split little bitty hairs to even finer hairs.
More information about the Python-list
mailing list