问题描述
下面的代码以这种方式读取一个数组,它为每个缓存行加载一个元素,假设它是64 字节,然后对每一行使用 clflush
并读取再次阵列。也就是说,二读的时间较短。我想知道为什么。似乎 clflush 不会使缓存行无效。
顺便说一句,缓存行是否正好由每行 64 个字节组成?
我有这个问题,因为我试图将步骤从 16 int
s 更改为 32 甚至 64,但是第二个阅读速度还是比较快的。
#include <time.h>
#include <cstdlib>
#include <cstdio>
#define ARR1_LEN 16384
#define PRINT_DUR {\
printf("%ld - %ld = %ld\n%.20Lf\n",t2,t1,t2-t1,((long double)(t2 - t1))/CLOCKS_PER_SEC);\
}
#define CLEAR_CACHE {\
asm("movq %1,%%rcx; movq %0,%%rax; label_%=: clflush (%%rax); addq $64,%%rax; loop label_%= ;"::"r"(arr1),"i"((ARR1_LEN>>5) -1):"rcx","rax");\
}
int main() {
int *arr1_ = (int*)malloc(sizeof(int) * ARR1_LEN + 64);
int temp;
if (!arr1_) {
fprintf(stderr,"Memory allocation error\n");
return 0;
}
int *arr1 = (int*)((((size_t)arr1_)+63)&0xffffffffffffffc0);
clock_t t1,t2;
t1 = clock();
for (int i = 0; i < (ARR1_LEN>>4); i++) {
temp = arr1[i<<4];
}
t2 = clock();
// __builtin___clear_cache(arr1,arr1 + ARR1_LEN -1); // It compiles into nothing at all
CLEAR_CACHE
PRINT_DUR
t1 = clock();
for (int i = 0; i < (ARR1_LEN>>4); i++) {
temp = arr1[(i<<4) + 32];
}
t2 = clock();
PRINT_DUR
free(arr1_);
return 0;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)