[Tutor] optimization: faster than for
elis aeris
hunter92383 at gmail.com
Sun Jul 1 05:46:23 CEST 2007
I found this on the net, and it's a different arrangement to using for
the author claims it will result in faster performance, but i can't find
documents on it, because I can't figure out which parts are parameters and
which parts on special words, for python.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070630/69499d52/attachment.htm
-------------- next part --------------
The operations with explicit loop counters have to be translated into Python byte code and must be interpreted. Implicit loop counter can be incremented by the core code (translated from C sources). Try this:
import timeit
sWhile = """\
x = 0
y = 0
number_scanned = 0
while x < 1024:
while y < 768:
y = y + 1
number_scanned = number_scanned + 1
y = 0
x = x + 1
"""
t = timeit.Timer(stmt=sWhile)
print "%.2f usec/pass" % (1000000 * t.timeit(number=10)/10)
sFor = """\
number_scanned = 0
for x in xrange(1024):
for y in xrange(768):
number_scanned = number_scanned + 1
"""
t = timeit.Timer(stmt=sFor)
print "%.2f usec/pass" % (1000000 * t.timeit(number=10)/10)
The sWhile and sFor are the multiline strings containing the equivalent code written using while and for loop respectively.
More information about the Tutor
mailing list