缓存未命中似乎工作不正常

Cache misses seem work not properly

本文关键字:工作 不正常 缓存      更新时间:2023-10-16

我想用这个简单的代码来检查缓存未命中,尝试分配例如数组包含3个元素,然后分配给包含30万个元素的数组,但在这两种情况下,对数组元素执行某些操作的时间都相当平均。

#include <iostream>
#include <cstdlib>
#include <ctime>

int main(int argc, char* argv[]) {
    const int TAB_SIZE = atoi(argv[1]);
    const int TEST_LEN = atoi(argv[2]);
    srand(time(NULL));
    int *tab = new int [TAB_SIZE];
    for(int i=0; i<TEST_LEN;++i) {
        int index = rand()%TAB_SIZE;
        // do something with random indexed array element
        tab[index] = index;
    }
    return 0;
}

这是我对3元素数组的输出:

marc@E540 ~/projects/simple/cache_test $ time ./a.out 3 100000000
real    0m1.236s
user    0m1.232s
sys     0m0.004s

对于30万元素阵列:

marc@E540 ~/projects/simple/cache_test $ time ./a.out 300000 100000000
real    0m1.375s
user    0m1.372s
sys     0m0.000s

第一个数组适合我的缓存,第二个不适合:

L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              3072K

当整个阵列都放在缓存中时,它不应该更快吗?或者差异并没有那么大吗?是否有更有效的方法来测试缓存?

对于我来说,在带有gcc 的centos上

[paul@pmcent work]$ time ./a.out 3 100000000
real    0m1.622s
user    0m1.603s
sys 0m0.000s
[paul@pmcent work]$ time ./a.out 300000 100000000
real    0m2.044s
user    0m2.023s
sys 0m0.000s
[paul@pmcent work]$ 

不是答案,但对于注释来说太大了