微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 CLFLUSH 没有任何影响?

如何解决为什么 CLFLUSH 没有任何影响?

下面的代码以这种方式读取一个数组,它为每个缓存行加载一个元素,假设它是64 字节,然后对每一行使用 clflush 并读取再次阵列。也就是说,二读的时间较短。我想知道为什么。似乎 clflush 不会使缓存行无效。

顺便说一句,缓存行是否正好由每行 64 个字节组成? 我有这个问题,因为我试图将步骤从 16 ints 更改为 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 举报,一经查实,本站将立刻删除。