了解空间和时间局部性
Understanding spatial and temporal locality
我在为我的架构期末学习时遇到了以下代码行:
for(i = 0; i <= N ;i++){
a[i] = b[i] + c[i];
}
问题是:“这段代码片段如何展示时间和空间局部性的例子?一定要考虑
数据和指令的内存引用。"
就空间局部性而言,我相信代码通过访问连续的内存位置(a[0] 然后 a[i] 等)来演示它。但是,我的困惑来自时间局部性。我不确定这段代码如何在短时间内引用同一位置?任何形式的帮助将不胜感激。
I'm not sure how this snippet of code references the same location within a small period of time?
如评论所述,变量 i
被访问得相当频繁,在您的示例中采用以下代码行:
a[i] = b[i] + c[i];
在这个例子中,a
、b
和c
大概都是指指向不同内存位置的数组类型(即使是连续的,仍然不同);然而,变量i
每次被引用时都是读取,然后确定要引用的数组的位置。
这样想:
get i from memory and store value in register x.
get value of b + [value in register x] from memory, store in register b.
get i from memory and store value in register y
get value of c + [value in register y] from memory, store in register c.
get i from memory and store value in register z
add value of [register b] to value in [register c] and store in memory location a + [value in register z]
优化编译器可能会看到这个时间局部性,而是执行类似于以下的操作:
get i from memory and store value in register i.
get value of b + [value in register i] from memory, store in register b.
get value of c + [value in register i] from memory, store in register c.
add value of [register b] to value in [register c] and store in memory location a + [value in register i]
正是通过这种方式,i
相邻引用之间具有时间上的接近性。
希望能帮到你。
I'm not sure how this snippet of code references the same location
within a small period of time.
除了之外,组成那个for循环的指令也存储在内存中。这些指令每次执行时都是memory/cache从"fetched"。由于这些指令中的每一条都在非常短的时间内执行了 N+1 次,这证明了时间局部性。
我在为我的架构期末学习时遇到了以下代码行:
for(i = 0; i <= N ;i++){
a[i] = b[i] + c[i];
}
问题是:“这段代码片段如何展示时间和空间局部性的例子?一定要考虑 数据和指令的内存引用。"
就空间局部性而言,我相信代码通过访问连续的内存位置(a[0] 然后 a[i] 等)来演示它。但是,我的困惑来自时间局部性。我不确定这段代码如何在短时间内引用同一位置?任何形式的帮助将不胜感激。
I'm not sure how this snippet of code references the same location within a small period of time?
如评论所述,变量 i
被访问得相当频繁,在您的示例中采用以下代码行:
a[i] = b[i] + c[i];
在这个例子中,a
、b
和c
大概都是指指向不同内存位置的数组类型(即使是连续的,仍然不同);然而,变量i
每次被引用时都是读取,然后确定要引用的数组的位置。
这样想:
get i from memory and store value in register x.
get value of b + [value in register x] from memory, store in register b.
get i from memory and store value in register y
get value of c + [value in register y] from memory, store in register c.
get i from memory and store value in register z
add value of [register b] to value in [register c] and store in memory location a + [value in register z]
优化编译器可能会看到这个时间局部性,而是执行类似于以下的操作:
get i from memory and store value in register i.
get value of b + [value in register i] from memory, store in register b.
get value of c + [value in register i] from memory, store in register c.
add value of [register b] to value in [register c] and store in memory location a + [value in register i]
正是通过这种方式,i
相邻引用之间具有时间上的接近性。
希望能帮到你。
I'm not sure how this snippet of code references the same location within a small period of time.
除了