为什么这段代码会多次产生缓存命中?

Why does this code generates a cache hit many times?

我理解缓存命中和未命中的概念,但不知何故,我并没有真正理解代码示例。下面的代码应该会生成很多 catch Hit,但为什么呢?我们在哪一部分看到了?我们现在如何让这段代码在大多数情况下找到缓存中的数据?

char array[1000]; 
for ( int i=0; i<1000; i++ ){ 
printf("%d ", array[i]); 
}

给定的代码是空间局部性参考的完美示例,因为array[i]是以连续和向前的方式访问的。根据Wikipedia:

Spatial locality

If a particular storage location is referenced at a particular time, then it is likely that nearby memory locations will be referenced in the near future. In this case it is common to attempt to guess the size and shape of the area around the current reference for which it is worthwhile to prepare faster access.

您可能还会注意到 i 变量表现出 时间局部性 ,在这种情况下,它很可能会被 optimizing compiler 放入 CPU注册.