Re: range() is not the best way to check range?



On 18/07/2006 12:41 PM, Summercoolness@xxxxxxxxx wrote:
it seems that range() can be really slow:

the following program will run, and the last line shows how long it ran
for:

import time

startTime = time.time()

a = 1.0
for i in range(0, 30000):
if i in range (0, 10000):
a += 1
if not i % 1000: print i

print a, " ", round(time.time() - startTime, 1), "seconds"


---------------------------------
the last line of output is
---------------------------------

10001.0 22.8 seconds

so if i change the line

if i in range (0, 10000):

to

if i >= 0 and i < 10000:

the the last line is

10001.0 0.2 seconds

so approximately, the program ran 100 times faster!

or is there an alternative use of range() or something similar that can
be as fast?

Some things to try:
1a. Read what the manual has to say about the range() function ... what does it produce?

1b. Read what the manual has to say about time.time() and time.clock(). Change over to using time.clock(). Change the round(...., 1) to (say) 4.

Alternatively, use something like this:

print "%.1f ... %.4f seconds" % (a, time.clock() - startTime)

1c. Repeat the two ways that you tried already.

2. First alternative:

Do this:

test_range = range(10000)

*once*, just after "a = 1.0".

and change your if test to

if i in test_range:

3. Now change that to:

test_range = set(range(10000))

4. Now forget about test_range, and change your if test to this:

if 0 <= i < 10000:

HTH,
John
.