title: Nested Loop Unrolling in C
body: <p>I want to optimize my code by using unrolling loop. I tried to apply unrolling but I think I cannot do it and I cannot see my problem. I want to apply unrolling loop to outer loop. </p>
  
  <p>This loops do transpose of matrix.</p>
  
  <p><em>This is my loop to apply unrolling loop:</em></p>
  
  <pre><code>void transpose(int dim, int *src, int *dst) {
      for (i = 0; i &lt; dim; i++)
          for (j = 0; j &lt; dim; j++)
              dst[j * dim + i] = src[i * dim + j];
  }
  </code></pre>
  
  <p>This is my unrolling loop:</p>
  
  <pre><code>void transpose(int dim, int *src, int *dst) {
      int i = 0, j = 0, dimi = 0, dimj = 0, tempi = 0;
  
      for (i = 0; i &lt; dim; i += 8) {
          for (j = 0; j &lt; dim; j++) {
              dimj = j * dim + i;
              dimi = i * dim + j;
              dst[dimj] = src[dimi];
  
              tempi = i + 1;
              if (tempi &lt; dim) {
                  dimj = j * dim + tempi;
                  dimi = tempi * dim + j;
                  dst[dimj] = src[dimi];
  
                  tempi += 1;
                  if (tempi &lt; dim) {
                      dimj = j * dim + tempi;
                      dimi = tempi * dim + j;
                      dst[dimj] = src[dimi];
  
                      tempi += 1;
                      if (tempi &lt; dim) {
                          dimj = j * dim + tempi;
                          dimi = tempi * dim + j;
                          dst[dimj] = src[dimi];
  
                          tempi += 1;
                          if (tempi &lt; dim) {
                              dimj = j * dim + tempi;
                              dimi = tempi * dim + j;
                              dst[dimj] = src[dimi];
  
                              tempi += 1;
                              if (tempi &lt; dim) {
                                  dimj = j * dim + tempi;
                                  dimi = tempi * dim + j;
                                  dst[dimj] = src[dimi];
  
                                  tempi += 1;
                                  if (tempi &lt; dim) {
                                      dimj = j * dim + tempi;
                                      dimi = tempi * dim + j;
                                      dst[dimj] = src[dimi];
  
                                      tempi += 1;
                                      if (tempi &lt; dim) {
                                          dimj = j * dim + tempi;
                                          dimi = tempi * dim + j;
                                          dst[dimj] = src[dimi];
                                      }
                                  }
                              }
                          }
                      }
                  }
              }
          }
      }
  }
  </code></pre>