P
Phlip
Luna said:My friend has three nested loops, each has 10000, 1000, 100
iterations, respectively.
What should be the most efficient way of layout out the three nested
loops?
Efficient for the programmer? or for the CPU?
for (i=0; i<10000; i++)
for (j=0; j<1000; j++)
for (k=0; k<100; k++)
Note those should use "for (int k = 0; ...". That follows the guideline that
you should give all variables the most restrictive scope possible.
Next, use /el Goog/ to search for "premature optimization is the root of all
evil". If you profiled these statements and figured which sequence was more
optimal, and you cross-profiled for the various hardware and swapper file
conditions you may meet, you will spend more time profiling than your
resulting program will save, in cumulative time, if it ran from now until
the Sun goes off main sequence.
Write whatever's easiest to program, write lots of unit tests, and leave
things easy to change. C++ will optimize simple loops like these very well.
If this code ever becomes your bottleneck, you should switch to a better
algorithm, such as a sparse array.