Timing While and For Loops in Python

bumsfeld 0 Tallied Votes 2K Views Share

The myth is around that while loop is faster than the corresponding for loop. I checked it out with Python module timeit, and came to surprising conclusion.

This snippet can easily be modified to time any of your functions you write.

# conclusion: while loop is slower than for loop

def while1():
    x = 0
    while x < 100:
        x += 1
    return x

print while1()  # test

def for1():
    x = 0
    for y in range(100):
        x += 1
    return x

print for1()

# using xrange()
def for2():
    x = 0
    for y in xrange(100):
        x += 1
    return x

print for2()

import timeit

print "Timing 100000 passes ..."

t = timeit.Timer('while1()', "from __main__ import while1")
elapsed = (10 * t.timeit(number=100000))
print "Function while1() takes %0.3f microseconds/pass" % elapsed

t = timeit.Timer('for1()', "from __main__ import for1")
elapsed = (10 * t.timeit(number=100000))
print "Function for1() takes %0.3f microseconds/pass" % elapsed

t = timeit.Timer('for2()', "from __main__ import for2")
elapsed = (10 * t.timeit(number=100000))
print "Function for2() takes %0.3f microseconds/pass" % elapsed

"""
typical result:
Function while1() takes 24.712 microseconds/pass
Function for1() takes 22.281 microseconds/pass
Function for2() takes 20.341 microseconds/pass
"""
N317V 10 Newbie Poster

Sorry, can't confirm that. A typical result from my machine (Python 2.4) looks like this.

Function while1() takes 21.923 microseconds/pass
Function for1() takes 23.813 microseconds/pass
Function for2() takes 21.976 microseconds/pass

Thanks for the snipped anyway.

Ene Uran 638 Posting Virtuoso

I get these results on a Windows Xp machine:

Function while1() takes 9.358 microseconds/pass
Function for1() takes 10.075 microseconds/pass
Function for2() takes 10.604 microseconds/pass

Wonder why xrange() is even slower?

Begjinner 0 Light Poster

Python 2.5, Windows XP, Pentium 4 at 2.60GHz and 1 GB memory.

100
100
100
Timing 100000 passes ...
Function while1() takes 12.069 microseconds/pass
Function for1() takes 13.216 microseconds/pass
Function for2() takes 13.082 microseconds/pass

Thanks for the nice snippet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.