extern short const_arr[N]
long func(short x)
{
static short array[N];
long res = 0;
int i;
for (i = N-1; i > 0;i--)
array[i] = array[i - 1]; // 1 arithmetic operation + 2 operations R/W = 11 cyc * (N-1)
array[0] = x; // 1 R/W = 5 cyc
for (i = 0; i < N; i++)
res += (long)array[i] * const_arr[i]; //2 R/W + 2 arithmetic op = 12 * N cyc
return res;
}
arr = {1,2,3,4}
const_arr = {8,9,10,11}
func(7)
arr = {1,2,3,7}
res =
2. Calculate the overall running time of the above C code as a function
of the array's length (n=N) .
Assume that:
A. Arithmetic operations (such as +,-,*,=,+=) cost one machine cycle.
B. Reading/Writing from an array element costs 5 machine cycles.
C. Loops have a zero overhead e.g.:
for (j = 0; j < n; j++)
arr[j] = a + b;
The cost of the loop is 6*n machine cycles (5 writing arr[j] ,1
calculating a+b).
"j = 0", "j < n", "j++" are not taken into consideration when
calculating cycle count.
***************************************
3. Lets assume that we add the following 2 new operators to the C language:
1) inc_mod(i, n); i++;
if (i >= n)
i = 0;
2) dec_mod(i, n); i--;
if (i < 0)
i = n - 1;
How can the function func() be optimized SIGNIFICANTLY in terms of run time.
Assume that the function func() will be called much more than N times
(thus optimizing the first multiplications of zero array elements, is not
worthwhile).