c - 如何优化缓存性能?

标签 c caching

我已经编写了一个使用数组的 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/

相关文章:

c - 间接预处理器替换 C

c - 奇偶校验如何找到偶数或奇数 1 的位?

c# - .Net - Redis 缓存 "object disposed exception"

django - 有什么理由不在 Django 中将 USE_ETAGS 与 CommonMiddleware 一起使用?

node.js - 如何使用redis在 Node 中缓存查询数据

c - 使用 C 传递/使用终端参数

c - 缺少这个 CRC-CCITT (Initial Value 0xFFFF) Encode 怎么办?

C 套接字 - 保留连接池以供重用 - s

c# - OptimisticConcurrencyException:使用共享的AppFabric缓存和相同的数据库的多个基于EF的应用程序

caching - 为什么缓存大小通常定义为素数?