Loops

Started by
4 comments, last by jfclavette 21 years ago
hypothetical: Would
  
long foo=0
long bar=0

long array[10000][5]= {3,6,2,6,8}

for (foo=0; foo<=9999; foo++)
{
  for (foo=0; foo<=5; foo++)
  {
    array[foo][bar]++;
  }
}
  
be faster than
  
long foo=0
long bar=0

long array[10000][5]= {3,6,2,6,8}

for (foo=0; foo<=9999; foo++)
{
  array[foo][0]++;
  array[foo][1]++;
  array[foo][2]++;
  array[foo][3]++;
  array[foo][4]++;
}
  
Assuming the situation is rigorously the same, but a little bit more complicated. Would the later be much faster?
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Advertisement
Theoretically the second should be faster. Also, I think this might be a little faster than the first example you gave.

  long foo=0;long bar=0;long array[10000][5]= {3,6,2,6,8};for (bar=0; bar<=5; bar++) {  for (foo=0; foo<=9999; foo++) {      array[foo][bar]++;  }}  

All I did was switch the inner and outer loops. Putting the loop with more iterations as the inner loop should be faster, I think. Also it might be possible to write it quite a bit faster using pointers rather than indexes into a 2D array. Maybe like this.

  long array[10000][5]= {3,6,2,6,8};long * p, * end = array + 49999;for (p=array; p != end; p++)    (*p)++;}  


[edited by - Russell on April 2, 2003 6:00:16 PM]
foo<=5;

This goes to 5.. meaning that it''ll try to access index [5] which is illegal.
use < not <=, and yes the second case would be marginally faster, depending on what goes on inside the second loop.

It would also be faster to flip it around:
for(int j=0; j<5; ++j)   for(int i=0; i<10000; ++i)      stuff(); 
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Careful everyone,

read up on multidimensional arrays in your C++ help index!

array [ a ] implies a-rows by b-colums.<br><br>the b is direct indexing, so your loop should be (optimized):<br><br>for(a…) {<br>for(b…) {<br>array[ a ] = xxx;<br>};<br>};<br><br>and not the other way around like this:<br><br>for(b…) {<br>for(a…) {<br>array[ a ] = xxx;<br>};<br>};<br><br>This second example is an order of magnitude slower.<br><br>www.cppnow.com<br><br><SPAN CLASS=editedby>[edited by - superdeveloper &#111;n April 2, 2003 11:58:44 PM]</SPAN>
Don't forget about loop inversion*.. some machines are faster with decrementing and comparing with zero than incrementing and comparing with a certain maximum. Text both loops with your machine to see which runs faster.

    foo = 10000while (--foo){   array[foo][4]++;   array[foo][3]++;   array[foo][2]++;   array[foo][1]++;   array[foo][0]++;}    


* "C Unleashed" by SAMS is a great book.

(silencer)

[edited by - -silencer- on April 3, 2003 2:43:44 AM]

This topic is closed to new replies.

Advertisement