Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-loop mechanism efficiency tips

As I am using for-loops on large multi-dim arrays, any saving on the for-loop mechanism itself is meaningful.

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

e.g. : counting down using uint instead of int and != 0 as stop instead of >0 allows the CPU to do less work (heard it once, not sure it is always true)

like image 837
gil Avatar asked Sep 28 '08 07:09

gil


3 Answers

One important suggestion: move as much calculation to the outer loop as possible. Not all compilers can do that automatically. For eample, instead of:

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

use:

for row = 0 to 999
    x = row * 1000
    y = row * 7
    for col = 0 to 999
        cell[x+col] = y + col
like image 172
paxdiablo Avatar answered Oct 25 '22 02:10

paxdiablo


Try to make your loops contiguous in memory, this will optimize cache usage. That is, don't do this:

for (int i = 0; i < m; i++)  
    for (j = 0; j < n; j++)  
        s += arr[j][i];
  • If processing images, convert two loops to one loop on the pixels with a single index.
  • Don't make loops that will run zero times, as the pipeline is optimized to assume a loop will continue rather than end.
like image 29
Lev Avatar answered Oct 25 '22 00:10

Lev


Have you measured the overhead? Do you know how much time is spent processing the for loops vs. how much time is spent executing your application code? What is your goal?

like image 36
Greg Hewgill Avatar answered Oct 25 '22 02:10

Greg Hewgill