Confused between Temporal and Spatial locality in real life code

后端 未结 4 890
陌清茗
陌清茗 2021-02-01 08:25

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]         


        
4条回答
  •  不要未来只要你来
    2021-02-01 08:48

    The outer loop is an example of spacial locality. It sequentially increments the address the inner for-loop calls.

    The inside loop demonstrates temporal locality. The exact same memory address is accessed ten times in a row, and multiplied by j each time.

    As for your first two questions, both i and j (loop counters) are very good examples of temporal locality.

    Locality is a measure applied by the cache to minimize the calls to memory. If an instruction needs to know the value of a memory address which is not already in the cache, it will access the memory and store all surrounding memory locations in the cache as well.

提交回复
热议问题