Question

We can do numeric iteration like:

for i in xrange(10):
    print i,

and in C-style:

i = 0
while i < 10:
    print i,
    i = i + 1

Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?

PS. I'm from C++ planet and pretty new on Python one.

Was it helpful?

Solution

I am sure the while version is slower. Python will have to lookup the add operation for the integer object on each turn of the loop etc, it is not pure C just because it looks like it!

And if you want a pythonic version of exactly the above, use:

print " ".join(str(i) for i in xrange(10))

Edit: My timings look like this. This is just a silly running loop without printing, just to show you what writing out "i += 1" etc costs in Python.

$ python -mtimeit "i=0" "while i < 1000: i+=1"
1000 loops, best of 3: 303 usec per loop
$ python -mtimeit "for i in xrange(1000): pass"
10000 loops, best of 3: 120 usec per loop

OTHER TIPS

Who cares? Seriously. If you want to know, use timeit package (you can invoke it from command line with -m).

But it doesn't matter at all, because the difference is negligible. And in general, Python is not a language that you choose if you want speed.

The first one.

You mean, faster to develop, right?

PS: It doesn't matter, machines these days are so fast that it is meaningless to ponder on micro optimizations, prior to identifying the bottlenecks using a thorough profiler.

They are both to avoid :-)

Generally speaking, each time I see an iteration over numbers, I see some non-pythonic code, that could be expressed in a better way using iterations over lists or generators.
Actually, I've said "pythonic", but it is all about readability. Using idiomatic code will increase readability, and ultimately also performance, because the compiler will better know how to optimize it.

Well, if you are after efficiency in numerical code, you ought to use numpy and scipy. Your integration can be quickly written as numpy.sum( numpy.arange( 10 ) )

If your program is too slow, try using psyco.

Don't worry about the kind of micro-optimisation in your question. Write your program to be maintainable (which includes following standard Python style so other programmers can read it easier).

In Python, the shorter and clearer version is always better. If I am not mistaken the range and xrange functions are not native, if you try xrange(sys.maxint+1) you will get an overflow error.

Besides, what the hell could this be useful for? If you are just printing 10 numbers, then surely readability counts a thousand times more - and I don't think you're going to print over a million numbers...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top