2
\$\begingroup\$

i have found this article on how to loop through multi-dimensional arrays quickly. http://nadeausoftware.com/articles/2012/06/c_c_tip_how_loop_through_multi_dimensional_arrays_quickly

I am using Method 6: Nested loops with linear array and single incrementing index. It says Method 8: Single loop with linear array and incrementing index is faster. but i require nested loops indexes as well. when i try to calculate the nested loops indexes via if clauses. my code slows down(at least worst than nested loop approach) can you recommend anything for calculating individual indexes.

 int x1=0,x2=0; 
  for (int i1 = 1; i1 <= 10000; i1++){
             for (int i = 0; i < 10000; i++){


                x1++;
                if(x1>100){
                    x1=0;
                    x2++;
                 }
                 a[i] = 0;
                 if (x1 > 10)
                 {
                     a[i] += a[i - 10*1];
                 }
                 if (x2 < 95)
                 {
                     a[i] += a[i + 5*100];
                 }
             }
         }

for multidimensional array structure a[x1][x2]. I want to calculate a[x1][x2]=a[x1-10][x2]+a[x1][x2+5] which a[x1][x2] is converted to a[x1+x2*100]

program code http://ideone.com/oKVdQI

Is there a way I can improve this code in terms of speed?

\$\endgroup\$
9
  • \$\begingroup\$ The ;lack of context and generic variable names makes this look like hypothetical code. If this isn't the case, then post the real code and its purpose. \$\endgroup\$
    – Jamal
    Commented Jan 27, 2016 at 22:00
  • \$\begingroup\$ The best way to improve this code is to remove the if statements from the loop. Branches inside loops kill performance. So convert the inner loop into three different loops (with no if statement). BUT a good compiler/hardware will automatically do that for you with branch prediction code stackoverflow.com/a/11227902/14065 \$\endgroup\$ Commented Jan 27, 2016 at 22:12
  • 1
    \$\begingroup\$ @jamal full function code is posted \$\endgroup\$ Commented Jan 27, 2016 at 22:19
  • 1
    \$\begingroup\$ Your first chunk of code mentions i1 but doesn't use it. Also, it appears to do nothing at all to the array a. So you basically have a 100 million step loop that does nothing? \$\endgroup\$
    – user1149
    Commented Jan 28, 2016 at 14:14
  • \$\begingroup\$ yes abstraction is a little bit hard to understand. but i wanted to improve the second code. \$\endgroup\$ Commented Jan 28, 2016 at 16:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.