gpt4 book ai didi

c - 如何优化缓存性能?

转载 作者:行者123 更新时间:2023-11-30 16:22:36 25 4
gpt4 key购买 nike

我已经编写了一个使用数组的 C 代码来了解我的 intel i7 8750 上的缓存行为,L1d = 32k,L2 = 258k,L3:912k,行大小为 64 字节,设置大小 = 8。 The trend I see for my code我试图理解从代码输出中获得的输出。如果 LRU 是缓存的替换策略,我的代码中还可以做些什么来确保获得最少的缓存未命中?

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<time.h>

#define BILLION 1000000000L

struct student
{
char name[64];
};

int main(int argc, char* argv[])
{

int m, i, p;
char* n;
char mn[64];
u_int64_t diff;
struct timespec start, end;
m = strtol(argv[1], &n, 0);

struct student* arr_student = malloc(m * sizeof(struct student));

for(u_int64_t i = 0; i < m; i++ )
{
strcpy(arr_student[i].name, "abc");
}

/* 100 runs to ensure cache warmup and linear access time calculation*/

for (int j = 0; j<100; j++){

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
for(u_int64_t i = 0; i < m; i+=8){
strcpy(mn,arr_student[i].name);
if(i < (m-8)){
strcpy(mn,arr_student[i+1].name);
strcpy(mn,arr_student[i+2].name);
strcpy(mn,arr_student[i+3].name);
strcpy(mn,arr_student[i+4].name);
strcpy(mn,arr_student[i+5].name);
strcpy(mn,arr_student[i+6].name);
strcpy(mn,arr_student[i+7].name);
}
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
}

diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;

printf("Time take for linear read operation only: %llu nanoseconds\n", (long long unsigned int) diff / 8 );

free(arr_student);

return 0;
}

我看到一个趋势,随着数组大小的增加,执行步幅为 8 的循环的执行时间会花费越来越多的时间。我期望它保持不变,并且只有当 CPU 必须在 L2 中查找时(即当数组大小增长超出 L1 可以容纳的范围时)才会增加。我期望看到这样的结果:https://www.google.com/search?q=cache+performance+trend+l1+l2&rlz=1C1GCEA_enUS831US831&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi9jqqApYrgAhXYFjQIHR39BtwQ_AUIDygC&biw=1280&bih=913#imgrc=5JVNAazx3drZvM :

为什么将 diff 除以 m 时会得到相反的趋势?我无法理解这种趋势。

请帮忙?

最佳答案

以下是一些有关内存对齐和代码优化的有用技巧:

一般来说,代码优化是时间和经验的问题。

关于c - 如何优化缓存性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374339/

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