473,770 Members | 4,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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?

Jul 18 '06 #1
45 8575
Su************@ gmail.com wrote:
it seems that range() can be really slow:
....
if i in range (0, 10000):
This creates a 10,000-element list and sequentially searches it. Of
course that's gonna be slow.

Jul 18 '06 #2
Su************@ gmail.com wrote:
or is there an alternative use of range() or something similar that can
be as fast?
You could use xrange:

leif@ubuntu:~$ python -m timeit -n10000 "1 in range(10000)"
10000 loops, best of 3: 260 usec per loop
leif@ubuntu:~$ python -m timeit -n10000 "1 in xrange(10000)"
10000 loops, best of 3: 0.664 usec per loop
Jul 18 '06 #3
Leif K-Brooks wrote:
Su************@ gmail.com wrote:
or is there an alternative use of range() or something similar that can
be as fast?

You could use xrange:

leif@ubuntu:~$ python -m timeit -n10000 "1 in range(10000)"
10000 loops, best of 3: 260 usec per loop
leif@ubuntu:~$ python -m timeit -n10000 "1 in xrange(10000)"
10000 loops, best of 3: 0.664 usec per loop
That's only because you're choosing a number that's early in the list.

~$ python -m timeit -n10000 "1 in xrange(10000)"
10000 loops, best of 3: 1.22 usec per loop
~$ python -m timeit -n10000 "9999 in xrange(10000)"
10000 loops, best of 3: 1.24 msec per loop

That's *milliseconds*, not microseconds.

Jul 18 '06 #4
On 18/07/2006 12:41 PM, Su************@ gmail.com 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
Jul 18 '06 #5
Su************@ gmail.com wrote:
so if i change the line
if i in range (0, 10000):
to
if i >= 0 and i < 10000:
[snip;]
is there an alternative use of range() or something similar that can
be as fast?

you've found that alternative yourself! just use the comparison operators...

in fact, you can write a little more compact as:
if 0 <= i < 10000 :
[sreeram;]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEvFGdrgn 0plK5qqURAlXhAJ 9mrod2ofLGlSCks nXqjzWDd0Y35wCg tx0f
+Fn3h07cOFT16Nv CX+DDqnY=
=Hk3J
-----END PGP SIGNATURE-----

Jul 18 '06 #6
On 2006-07-18, Su************@ gmail.com <Su************ @gmail.comwrote :
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"
or is there an alternative use of range() or something similar that can
be as fast?
Creating and then searching a 10,000 element list to see if a
number is between two other numbers is insane.

Using xrange as somebody else suggested is also insane.

If you want to know if a number is between two other numders,
for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:

--
Grant Edwards grante Yow! ANN JILLIAN'S HAIR
at makes LONI ANDERSON'S
visi.com HAIR look like RICARDO
MONTALBAN'S HAIR!
Jul 18 '06 #7
Grant Edwards wrote:
for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:
I'm assuming you used Python's compound comparison as opposed to the
C-style of and'ing two comparisons together to emphasize the fact it is
god's chosen way of doing this ;-)

Jul 18 '06 #8
In <11************ **********@h48g 2000cwc.googleg roups.com>, tac-tics
wrote:
Grant Edwards wrote:
>for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:

I'm assuming you used Python's compound comparison as opposed to the
C-style of and'ing two comparisons together to emphasize the fact it is
god's chosen way of doing this ;-)
Pete doesn't like to be called god in public. ;-)

Ciao,
Marc 'BlackJack' Rintsch
Jul 18 '06 #9
Grant Edwards <gr****@visi.co mwrote:
Creating and then searching a 10,000 element list to see if a
number is between two other numbers is insane.
Using xrange as somebody else suggested is also insane.
Aye to both
If you want to know if a number is between two other numders,
for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:
Sets are pretty fast too, and have the advantage of flexibility in
that you can put any numbers in you like

$ python2.4 -m timeit -s 's=range(0,1000 0); i=5000' 'i in s'
1000 loops, best of 3: 228 usec per loop

$ python2.4 -m timeit -s 's=set(range(0, 10000)); i=5000' 'i in s'
1000000 loops, best of 3: 0.312 usec per loop

$ python2.4 -m timeit -s 'i=5000' '0 <= i < 10000'
1000000 loops, best of 3: 0.289 usec per loop

The below prints

range) That took 21.512 seconds: result 10001.0
set) That took 0.023 seconds: result 10001.0
comparison) That took 0.024 seconds: result 10001.0

............... ............... ............... ............... .

import time

start = time.time()
a = 1.0
for i in range(0, 30000):
if i in range(0, 10000):
a += 1
dt = time.time() - start
print "range) That took %.3f seconds: result %s" % (dt, a)

start = time.time()
a = 1.0
mine = set(range(0, 10000))
for i in range(0, 30000):
if i in mine:
a += 1
dt = time.time() - start
print "set) That took %.3f seconds: result %s" % (dt, a)

start = time.time()
a = 1.0
mine = set(range(0, 10000))
for i in range(0, 30000):
if 0 <= i < 10000:
a += 1
dt = time.time() - start
print "comparison ) That took %.3f seconds: result %s" % (dt, a)

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jul 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
7483
by: Chris Dutrow | last post by:
I searched around on the net for a bit, couldn't find anything though. I would like to find some code for a function where I input A Range Of Integers For example: Function( 1, 100 ); And the function will return me an array holding a random subset of integers in that range of a size that I specify So the Function would Probabaly look something like this:
0
1014
by: illo | last post by:
hello guys... a little but very imposrtant question... I have a broadband connection in my office, and i would like to use this connection also from my house (150 meters from the office)... I bought a router and 2 range extenders of belkin.... With the router everything functions very well,
5
5950
by: sameer_deshpande | last post by:
Hi, I need to create a partition table but the column on which I need to create a partition may not have any logical ranges. So while creating or defining partition function I can not use any range. like CREATE PARTITION FUNCTION my_part_func (NUMERIC(7)) AS RANGE LEFT FOR VALUES (1,100,1000);
3
2852
by: toton | last post by:
Hi, I want ro iterate over a few container class within a range specified, instead of begin & end. How to construct a range class, which takes start & end, and iteration is available within that range only. Itaration may be const, bidiractional, forward or backward. Say I have a vector or other container class, like vector<intvec; and want to return a range class like range(vec.begin()+5,
3
4133
by: Alexander Higgins | last post by:
Hello, I would like to thank everyone for there help in advance. I have form which is using an iframe as a Rich Text Editor. Everything works as expected in IE but I have two issues with Firefox. I am using the following to make the frame editable: tmp=document.getElementById("adeditor").contentWindow.document tmp.designMode="On";
2
2214
by: Joe Goldthwaite | last post by:
I've been playing with Python a bit. Doing little performance benchmarks and working with Psyco. It's been fun and I've been learning a lot. For example, in a previous post, I was looking for a way to dynamically add new runtime function to a class. Martin told me to use a class instance variable instead. It turns out that's faster than hard coding a list of functions. Thanks Martin. I read that the range function builds a list and...
10
3019
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
0
9602
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9439
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9882
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8905
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7431
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5326
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2832
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.