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