Maybe for the simple sum you can just use the sum builtin:<div><div>python -m timeit -s  'sum((10,)*10000)'</div><div>10000000 loops, best of 3: 0.0985 usec per loop</div></div><div><br></div><div>About the loop in general it's a good practice to use list comprehension and generator expressions<br>
<br><div class="gmail_quote">2010/9/2 Michael Kreim <span dir="ltr"><<a href="mailto:michael@perfect-kreim.de">michael@perfect-kreim.de</a>></span><br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
Hi,<br>
<br>
I was comparing the speed of a simple loop program between Matlab and Python.<br>
<br>
My Codes:<br>
$ cat addition.py<br>
imax = 1000000000<br>
a = 0<br>
for i in xrange(imax):<br>
    a = a + 10<br>
print a<br>
<br>
$ cat addition.m<br>
imax = 1e9;<br>
a = 0;<br>
for i=0:imax-1<br>
    a = a + 10;<br>
end<br>
disp(a);<br>
exit;<br>
<br>
The results look like this:<br>
$ /usr/bin/time --verbose python addition.py<br>
10000000000<br>
        Command being timed: "python addition.py"<br>
        User time (seconds): 107.30<br>
        System time (seconds): 0.08<br>
        Percent of CPU this job got: 97%<br>
        Elapsed (wall clock) time (h:mm:ss or m:ss): 1:50.09<br>
        [...]<br>
<br>
$ /usr/bin/time --verbose matlab -nodesktop -nosplash -r "addition"<br>
[...]<br>
    1.0000e+10<br>
        Command being timed: "matlab -nodesktop -nosplash -r addition"<br>
        User time (seconds): 7.65<br>
        System time (seconds): 0.18<br>
        Percent of CPU this job got: 94%<br>
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:08.25<br>
        [...]<br>
<br>
Unfortunately my Python Code was much slower and I do not understand why.<br>
<br>
Are there any ways to speed up the for/xrange loop?<br>
Or do I have to live with the fact that Matlab beats Python in this example?<br>
<br>
Thanks a lot for your answers.<br>
<br>
With best regards,<br><font color="#888888">
<br>
Michael</font><div><div></div><div class="h5"><br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br></div>