### C code optimization benchmark

Steve Oualline talks about C code optimization on his book: Practical C Programming. I was curious about the real performance gains. The benchmark test results are at the end of the post.

How can this C code be optimized?

#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

int x,y;

for (x = 0; x < X_SIZE; ++x){

for (y = 0; y < Y_SIZE; ++y){

matrix[x][y] = -1;

}

}

}

void main()

{

initmatrix();

} The first suggested optimization is to use the "register" qualifier for the indexes variables x and y:

#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

for (x = 0; x < X_SIZE; ++x){

for (y = 0; y < Y_SIZE; ++y){

matrix[x][y] = -1;

}

}

}

void main()

{

initmatrix();

} Then the optimization suggestion is to order the for loops so that the innermost for is the most complex:

#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

register int x,y;

How can this C code be optimized?

**matrix1.c**#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

int x,y;

for (x = 0; x < X_SIZE; ++x){

for (y = 0; y < Y_SIZE; ++y){

matrix[x][y] = -1;

}

}

}

void main()

{

initmatrix();

} The first suggested optimization is to use the "register" qualifier for the indexes variables x and y:

**matrix2.c**#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

**register**int x,y;for (x = 0; x < X_SIZE; ++x){

for (y = 0; y < Y_SIZE; ++y){

matrix[x][y] = -1;

}

}

}

void main()

{

initmatrix();

} Then the optimization suggestion is to order the for loops so that the innermost for is the most complex:

**matrix3.c**#define X_SIZE60

#define Y_SIZE30

int matrix[X_SIZE][Y_SIZE];

void initmatrix(void)

{

register int x,y;

**f…**

**
**