[Python-Dev] xrange accepting non-ints (original) (raw)

Neal Norwitz nnorwitz at gmail.com
Thu Aug 24 17:43:38 CEST 2006


I've been working on enhancing xrange and there are a bunch of issues to consider. I've got pretty much complete implementations in both C and Python. Currently xrange is 2 objects: range and the iter. These only work on C longs. Here's what I propose:

2.6:

The idea is to expand xrange's capabilities so that it can replace range in 3k.

I've profiled various combinations. Here are the various results normalized doing xrange(0, 1e6, 1):

Run on all integer (32-bit) values for start, step, end: C xrange and iter: 1 Py xrange w/C iter: 1 Py xrange w/Py iter (gen): 5-8 Py xrange w/Py iter (class): ~30

So having xrange in python is the same speed as if xrange is written in C. The important part is that the iterator needs to be written in C for speed. If we use a generator, something like:

    while value < end:
        yield value
        value += step

The result is ~5 times slower in a release build and 8 times slower in a debug build than with an iterator implemented in C. Using a generator means that there is no length_hint. If we go with a full class that has a length_hint the result was ~32 times slower in a debug build.

The Python impl is about 1/10th the size of the C impl, though is lacking some comments.

Run on Python longs the result is somewhat interesting. The Python based iterator is faster. There's probably a bug in the C version, but given that there is a lot of object allocation, I wouldn't expect the C version to ever be much faster than a similar Python version. Plus the Python version is trivial (same as above) for ints or longs. The C version for longs is quite a bit of code.

Run on all Python longs (still 0..1e6, but sys.maxint..(sys.maxint + 1e6) is the same): C xrange and iter: 1.4 Py xrange w/C iter: not tested Py xrange w/Py iter (gen): 1 Py xrange w/Py iter (class): 4

Caveats:

Hopefully this is all understandable. If I left anything out, Thomas will remind me.

n



More information about the Python-Dev mailing list