To increase the efficiency of the loop mechanism

Since I use for-loops on large multi-disk arrays, any savings on the for-loop mechanism itself makes sense.

Accordingly, I am looking for any advice on how to reduce this overhead.

e.g .: a countdown using uint instead of int and! = 0 as stop instead of> 0 allows the processor to do less work (heard once, not sure if this is always true)

+5
source share
13 answers

First, do not sweat small things. Details, such as counting and counting, are usually irrelevant during operation. People, as you know, are poorly versed in areas of code that need to be accelerated. Use a profiler. Do not pay any attention to any part of the loop that does not repeat unless the profiler says otherwise. Remember that what is written in the inner loop is not necessarily executed in the inner loop, as modern compilers are pretty smart to avoid unnecessary repetition.

, . , . , , , . (, , , , 80% . , , .)

, , . ++ pre-increment (++ i), post-increment (i ++) . , , , .

+4

: . . , :

for row = 0 to 999
    for col = 0 to 999
        cell[row*1000+col] = row * 7 + col

:

for row = 0 to 999
    x = row * 1000
    y = row * 7
    for col = 0 to 999
        cell[x+col] = y + col
+12

, . , :

for (int i = 0; i < m; i++)  
    for (j = 0; j < n; j++)  
        s += arr[j][i];
  • .
  • , , , , , .
+9

? , for ? ?

+6

Loop-unrolling . :

for (i=0; i<N; i++) {
  a[i]=...;
}

:

for (i=0; i<N; i+=4) {
  a[i]=...;
  a[i+1]=...;
  a[i+2]=...;
  a[i+3]=...;
}

, N 4 .

+5

, , . , , :

for (int i = 0; i < 10; i++) { /* ... */ }

int i = 0;
while (i < 10) {
    // ...
    i++;
}

/ for while while. Foreach /, , , while/while. , .

, .

: , .

+4

BTW, -, pre-increment. , .

:

  • i++;

    :

    int postincrement( int &i )
    {
    int itmp = i;
    i = i + 1;
    return itmp;
    }

  • ++i;

    :

    int preincrement( int &i )
    {
    i = i + 1;
    return i;
    }

+4

@Greg. , , . , , . " - "!

+3

O (n ^ d) (d = ), , , , INTO , . - .

+1

, short int for-loop, Int16 ?

+1

, , , , , . , , , . , .

0

, . ? , . , , 2 , , .

, - , , , , , , L1/L2 ( L1, ).

Again, I would look at what's inside the loop first, where most of the gains (> 99%) will be, and not external loop plumbing.

But then again, if your loop code is related to I / O, then any time spent optimizing is lost.

0
source

There is some relevant information among the answers to another question about the stack, how the cache works . I found the Ulrich Drapper article mentioned in this is especially useful.

0
source

All Articles