gpt4 book ai didi

c++ - 如何想出一个高缓存未命中率的例子?

转载 作者:可可西里 更新时间:2023-11-01 16:36:27 25 4
gpt4 key购买 nike

我正在尝试编写一个具有高缓存未命中率的示例程序。我想我可以尝试像这样逐列访问矩阵:

#include <stdlib.h>

int main(void)
{
int i, j, k;

int w = 1000;
int h = 1000;

int **block = malloc(w * sizeof(int*));
for (i = 0; i < w; i++) {
block[i] = malloc(h * sizeof(int));
}

for (k = 0; k < 10; k++) {
for (i = 0; i < w; i++) {
for (j = 0; j < h; j++) {
block[j][i] = 0;
}
}
}

return 0;
}

当我使用 -O0 标志编译它并使用 perf stat -r 5 -B -e cache-references,cache-misses ./a.out 运行时给我:

 Performance counter stats for './a.out' (5 runs):

715,463 cache-references ( +- 0.42% )
527,634 cache-misses # 73.747 % of all cache refs ( +- 2.53% )

0.112001160 seconds time elapsed ( +- 1.58% )

这对我的目的来说已经足够好了。但是,如果我继续将矩阵大小更改为 2000x2000,它会给出:

 Performance counter stats for './a.out' (5 runs):

6,364,995 cache-references ( +- 2.32% )
2,534,989 cache-misses # 39.827 % of all cache refs ( +- 0.02% )

0.461104903 seconds time elapsed ( +- 0.92% )

如果我将它进一步增加到 3000x3000,我会得到:

 Performance counter stats for './a.out' (5 runs):

59,204,028 cache-references ( +- 1.36% )
5,662,629 cache-misses # 9.565 % of all cache refs ( +- 0.11% )

1.116573625 seconds time elapsed ( +- 0.32% )

这很奇怪,因为随着大小的增加,我希望获得更多的缓存未命中率。我需要尽可能独立于平台的东西。计算机体系结构类(class)很久以前所以任何见解都会受到欢迎..

注意事项

我说我需要一些相对平台独立的东西,但这些仍然是我的规范:

  • 英特尔® 酷睿™ i5-2467M
  • 4 GiB 内存
  • 64 位 ubuntu 12.04

最佳答案

当心现代 CPU 中的自动预取 - 它通常可以检测跨步访问。也许尝试随机访问模式,例如:

int main(void)
{
int i;

int n = 1000 * 1000;

int *block = malloc(n * sizeof(int));

for (i = 0; i < n / 10; i++) {
int ri = rand() % n;
block[ri] = 0;
}

return 0;
}

关于c++ - 如何想出一个高缓存未命中率的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14635562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com