computer-sciencecpu-architecturecache-locality

Confused between Temporal and Spatial locality in real life code


I was reading this question, I wanted to ask more about the code that he showed i.e

for(i = 0; i < 20; i++)
    for(j = 0; j < 10; j++)
        a[i] = a[i]*j;

The questions are,

  1. I understand temporal locality, I think that references to i and j should be temporal locality. Am I right?
  2. I also understand spatial locality, as the question I linked answers that references to a[i] should be spatial locality. Am I right?
  3. The person said,

    "The inner loop will call same memory address when accessing a[i] ten times so that's an example for temporal locality I guess. But is there spatial locality also in the above loop?"

    I don't agree with his guess. As the references generated by a[i] should be spacial locality (They will be referencing the next element in the block). Am I right?


Solution

  • First off, references to var can be temporally local or spatially local not temporal locality, which is improper grammar. Minor point.

    Now, on to your questions.

    1. The principle of Temporal locality states that two instructions reference the same location within a relatively short timeframe. For example, in the code given, a[i] is referenced frequently, with instructions like a[i] = a[i] * 2 and a[i] = a[i] * 3 being executed very close together. If we are looking at this scope, we could say that references to j and a[i] are temporally local. References to i are also temporally local, because i is referenced every time a[i] is. However, if the last line of the given code read something like a[j] = a[j] * j, then references to i would not be temporally local, at least in the scope of the inner loop[1].

    2. The principle of Spatial locality states that two instructions reference contiguous memory locations. References to a[i] are a good example of this, as one can assume (most of the time) that a[0] and a[1] will be next to each other in memory.

    3. The first two basically cover this, but the quoted text is correct, and the code also demonstrates spatial locality.

    [1] - Generally, when you are talking about locality, it will be in the context of a given level in the memory hierarchy, whether it be RAM or the L1 cache or what have you. In all but the most limited sense, references to both i and j are temporally local.