faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 6 people (83%) answered Yes
Recently 4 of 5 people (80%) answered Yes

Entry

Help with first Python program

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 46, Tim Peters


"""
Packages: miscellaneous.performance;basic_applications.loops
"""

"""
[Daniel T.]
> for x in range(100000):

[William Park]
> (A) Since you simply looping 100000 times, it's better to write
> 	x = 0
> 	while x < 100000:
> 	    ...
> 	    x = x + 1

[andrew@intertrader.com]
> ...
> Why is the while loop better?

It's generally not.

> Is it faster?

Generally slower; play with the attached.  You'll probably find that the
"range" version is significantly faster than the "while" one; and unless
you're Guido running on some goofy SPARC <wink>, you'll probably find that
"xrange" is quicker than "range".  If the loop count is *very* large, though
(depending on your free memory), "range" will grind your disk to dust but
"while" and "xrange" won't.

> Does the range statement use a lot of memory?

Yup!  range(n) constructs an explicit list of n ints before the loop begins.
That's rarely worth worrying about, but when it is the xrange variant avoids
it.

> ...

trust-no-one<wink>-ly y'rs  - tim
"""

def loop1(n):
    for i in range(n): pass

def loop2(n):
    for i in xrange(n): pass

def loop3(n):
    i = 0
    while i < n: i = i + 1

def timeit(f):
    from time import clock
    print "times for", f.__name__,
    for i in range(3):
        start = clock()
        x = f(100000)
        finish = clock()
        print finish - start,
    print

timeit(loop1)
timeit(loop2)
timeit(loop3)