range() vs xrange() Python2|3 issues for performance

Chris Angelico rosuav at gmail.com
Tue Aug 2 05:52:59 EDT 2011


On Tue, Aug 2, 2011 at 10:20 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> What version of Py3 were you using? If you used the latest, maybe even the
> latest hg version, you will notice that that's substantially faster for
> integers than, e.g. 3.1.x.
>

I just tried this out, using a slightly modified script but the same guts:

-----
import sys
print(sys.version)

import time
def PNums(q):
   start=time.clock()
   for i in range(2, q):
       m = 1
       s = 0
       while m <= i/2:
           if not i%m:
               s += m
           m += 1
       if i == s:
            print(i)
   print("Time: %f"%(time.clock()-start))
   return

# PNums(33550337)
PNums(10000)

-----

On my dual-core Windows laptop (it always saturates one core with
this, leaving the other for the rest of the system), the results show
no statistically significant difference between xrange and range in
Python 2, but notably slower overall performance in Python 3:

2.4.5 (#1, Dec 15 2009, 16:41:19)
[GCC 4.1.1]
Time: 14.474343
Using xrange: 14.415412

2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)]
Time: 8.990142
Using xrange: 9.015566

3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]
Time: 24.401461

Since I don't have a build environment in which to test the latest
from hg, I switched to a Linux box. The following timings therefore
cannot be compared with the above ones.

3.3a0 (default:b95096303ed2, Jun  2 2011, 20:43:01)
[GCC 4.4.5]
Time: 34.390000

2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5]
Time: 13.730000
Using xrange: 13.670000

My 3.3a0 is freshly pulled from hg, although I'm not sure if
sys.version has been correctly built. Once again, 2.6.6 shows no
significant difference between range and xrange, but 3 is noticeably
slower than 2. (I did several runs, but the variance between the runs
wasn't significant.)

Of course, this is all fairly moot; if you're doing really heavy
number crunching, CPython isn't the platform to use.

ChrisA



More information about the Python-list mailing list