472,119 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,119 software developers and data experts.

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 1944
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
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.