Speed-up for loops
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Sep 5 11:00:32 EDT 2010
On Fri, 03 Sep 2010 21:17:44 +0100, BartC wrote:
> I'm not sure the Python developers were interested in getting fast
> loops.
>
> For-loops which iterate between two numbers are amongst the easiest
> things to make fast in a language. Yet originally you had to use:
>
> for i in range(N):
I don't have any versions of Python prior to version 1.5, but as far back
as that there was always a choice between creating a list with range()
and a lazy iterator with xrange().
> which (if I understood correctly) actually created a list of N objects,
> populated it with the values 0, 1, 2...N-1 (presumably using a more
> sensible loop), then iterated between the values of the list!
By "more sensible", do you mean "in C code"? If so, then you are correct.
> So Python had the distinction of being one of the slowest languages in
> which to do nothing (ie. running an empty loop).
Nonsense.
[steve at sylar ~]$ time python test.py
real 0m3.441s
user 0m2.969s
sys 0m0.024s
[steve at sylar ~]$ time perl test.pl
real 0m3.490s
user 0m2.722s
sys 0m0.011s
[steve at sylar ~]$ time ruby test.rb
real 0m11.875s
user 0m6.740s
sys 0m3.995s
The difference between an empty loop in Python and Perl is insignificant,
and much faster than Ruby (at least the specific version of Ruby
installed on my machine, 1.8.6).
And if you want to see the code I ran:
[steve at sylar ~]$ cat test.*
# perl
for ($i = 0; $i < 10_000_000; ++$i) {
1;
}
# python
for i in xrange(10000000):
1
# ruby
for i in 0...10000000
1
end
Just for comparisons' sake:
[steve at sylar ~]$ gpc empty_test.p
[steve at sylar ~]$ time ./a.out
real 0m0.106s
user 0m0.070s
sys 0m0.004s
[steve at sylar ~]$ cat empty_test.p
program main(input, output);
var
i: integer;
begin
for i := 0 to 10000000 do
begin
end;
end.
Of course, a real optimizing compiler would realise that the Pascal code
did nothing at all, and compile it all away to an empty a.out file...
--
Steven
More information about the Python-list
mailing list