performance of Nested for loops

Q

querypk

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
 
C

Charles Krug

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.
 
L

Larry Bates

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
 
A

Andrew Dalke

querypk said:
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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top