C - 缓存行和关联

Lar*_*rry 7 memory arrays optimization caching computer-architecture

上下文

阅读有关缓存优化的文章(与循环中的缓存行关联..)

问题与此上下文有关:1024个整数数组.

大小:cpu cache 64k,缓存行32bytes,整数size:4 bytes.

英特尔核心2二重奏

根据我的cpu,8个整数适合缓存行.

[0,1,2,3,4,5,6,7,8,9,10,...,1023]
         ^
If I want to access 4 and go downward, 3,2,1 and 0 will be loaded already. 5,6,7 are loaded uselessly.

[0,1,2,3,4,5,6,7,8,..,1023]
               ^
If I want to access 7 and go downward, all the next elements will be in cache already. if I want to go upward, according to my cpu I will have to load another cache line immediatly after the arr[7] read.
Run Code Online (Sandbox Code Playgroud)

我对么 ?

走得更远

但是什么告诉我,arr [4]不在一个会导致缓存行加载的地址而不是arr [7]?如果我的陈述是真的,我们不应该只考虑数组内对齐,而是考虑程序的整个内存对齐,以尽量减少缓存浪费,对吗?

chr*_*hrk 2

就您的主要问题而言,是的,您在这两种情况下都是正确的。

在第二种情况下,arr[7]加载到哪里并且可能想要继续向上,您应该注意编译器或某些预取机制可能会考虑此类数据的空间局部性,从而提高性能。

更进一步,读取数组中的其他地址确实可能会导致缓存行加载,而不是arr[7]数组在内存中未正确对齐,但在这种情况下,对齐不取决于您,而是取决于编译器。