469,951 Members | 2,340 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,951 developers. It's quick & easy.

performance of Nested for loops

Is there a better way to code nested for loops as far as performance is
concerned.

what better way can we write to improve the speed.
for example:
N=10000
for i in range(N):
for j in range(N):
do_job1
for j in range(N):
do_job2

Jul 19 '05 #1
3 1888
On 20 May 2005 15:35:10 -0700, qu*****@gmail.com <qu*****@gmail.com>
wrote:
Is there a better way to code nested for loops as far as performance is
concerned.

what better way can we write to improve the speed.
for example:
N=10000
for i in range(N):
for j in range(N):
do_job1
for j in range(N):
do_job2


What do you see when you profile the code?

Premature Optimization is the root of all manner of evil and all that
good stuff.

Jul 19 '05 #2
You can use xrange(N) that way Python doesn't have
to build the 10000 item lists 20000 times. Other than
that one would need to know why you would call do_job1
and do_job2 10000 times each inside a 10000 iteration
loop. Most VERY large performance gains are due to
better algorithms not code optimization.

Larry Bates
qu*****@gmail.com wrote:
Is there a better way to code nested for loops as far as performance is
concerned.

what better way can we write to improve the speed.
for example:
N=10000
for i in range(N):
for j in range(N):
do_job1
for j in range(N):
do_job2

Jul 19 '05 #3
querypk wrote:
Is there a better way to code nested for loops as far as performance is
concerned.

what better way can we write to improve the speed.
for example:
N=10000
for i in range(N):
for j in range(N):
do_job1
for j in range(N):
do_job2


For this case compute the range once

range_10000 = range(10000)
for i in range_10000:
for j in range_10000:
do_job1()
for j in range_10000:
do_job2()

Using xrange(10000) may be faster but you would need to test
that out for your case.

Andrew
da***@dalkescientific.com

Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

25 posts views Thread by chad | last post: by
1 post views Thread by Scott | last post: by
1 post views Thread by Tim Smith | last post: by
3 posts views Thread by pertheli | last post: by
reply views Thread by Palle Girgensohn | last post: by
46 posts views Thread by Neptune | last post: by
8 posts views Thread by Nathan Sokalski | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.