Speed-up for loops
gabriele.lanaro at gmail.com
Sun Sep 5 00:54:14 CEST 2010
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
2010/9/2 Michael Kreim <michael at perfect-kreim.de>
> I was comparing the speed of a simple loop program between Matlab and
> 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;
> The results look like this:
> $ /usr/bin/time --verbose python addition.py
> 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"
> 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
> Thanks a lot for your answers.
> With best regards,
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list