I was studying for my architecture final and came across the following lines of code:
for(i = 0; i <= N ;i++){
a[i] = b[i] + c[i];
}
The question is: "How does this code snippet demonstrate examples of temporal and spatial locality? Be sure to consider memory references for both data and instructions."
In terms of spatial locality I believe the code demonstrates it by accessing contiguous memory locations (a[0] then a[i] etc). However, my confusion comes with temporal locality. I'm not sure how this snippet of code references the same location within a small period of time? Any sort of help would be greatly appreciated.
As has been commented, the variable
i
is accessed quite frequently, take the following line of code in your example:In this example,
a
,b
andc
all presumably refer to array types pointing to different memory locations (even if contiguous, still different); however, the variablei
is read each time it is referenced to then determine the location of the array to reference.Think of it this way:
An optimizing compiler would likely see this temporal locality and instead do something similar to the following:
It is in this way that
i
has a temporal proximity between adjacent references.I hope that can help.