Following is code for a C program that accesses elements in two different two di
ID: 3548310 • Letter: F
Question
Following is code for a C program that accesses elements in two different two dimensional array.
static int anArray[5][4]={{1, 2, 3, 4}, {10, 20, 30, 40}, {16, 15, 14, 13}, {11, 21, 31, 41}, {15, 14, 13, 12}};
static short mulArray[5][4] = {{2, 2, 3, 5}, {3, 5, 1, 2}, {3, 4, 5, 6}, {2, 7, 1, 2}, {8, 7, 2, 2}};
int main (int argc, char **argv) {
int idx, jdx;
for (jdx = 0; jdx < 4; jdx++) {
for (idx = 0; idx<5; idx++) {
anArray[idx][jdx] = anArray[idx][jdx] * mulArray[idx][jdx] + 1;
}
}
}
Suggest a simple change to the code that will make better use of spatial locality and increase the cache hit rate.
Unroll the for loop so that two elements are calculated in each iteration, instead of one.
Explanation / Answer
- Change the order for accessing the memory location of the array for better cache hit
- Add an extra line of code for calculation of two elements at a time
static int anArray[5][4]={{1, 2, 3, 4}, {10, 20, 30, 40}, {16, 15, 14, 13}, {11, 21, 31, 41}, {15, 14, 13, 12}};
static short mulArray[5][4] = {{2, 2, 3, 5}, {3, 5, 1, 2}, {3, 4, 5, 6}, {2, 7, 1, 2}, {8, 7, 2, 2}};
int main (int argc, char **argv) {
int idx, jdx;
for (idx = 0; idx < 5; idx+2) {
anArray[idx][jdx] = anArray[idx][jdx] * mulArray[idx][jdx] + 1;
anArray[idx][jdx] = anArray[idx+1][jdx+1] * mulArray[idx+1][jdx+1] + 1;
}
}
}