c - 为了提高缓存命中率,我该如何修改程序

标签 c

Change the program to improve the cache hit rate and write the revised program. In addition, for the same cache (8word block size) in (a), compute the data cache miss rate.

这是我的任务。

如何修改此代码?

int a[1024], b[1024], c[1024], d[1024];

void main(){ 
   int s=0;
   for(int i=0; i<1024; ++i){
     s += a[i]*b[i]+c[i]*d[i];
   }
}

假设起始地址为a , b , c , d0x0000 , 0x1000 , 0x2000 ,和0x3000 , 分别。 所以由于起始地址的原因,这条cod的错过率是100%。

最佳答案

基本的改进是使用结构数组:

struct ABCD
{
    int a;
    int b;
    int c;
    int d;
}
ABCD v[1024];

void main()
{
    int s=0; 
    for(int i=0; i<1024; ++i) 
    {
        s += v[i].a*v[i].b+v[i].c*v[i].d;
    }
}

这样,您只需在每个位置寻呼一次。所有内存访问都将在最近访问的数据附近完成。

如果无法更改数据格式,也许预期的解决方案是循环数据两次,+ 运算符的每一侧各循环一次。那么解决方案将如下所示:

void main()
{
    int s=0; 
    for(int i=0; i<1024; ++i) 
    {
        s += a[i]*b[i];
    }
    for(int i=0; i<1024; ++i) 
    {
        s += c[i]*d[i];
    }
}

(我只是注意到 C 标记,而不是 C++。因此,结构声明周围可能缺少修复)

关于c - 为了提高缓存命中率,我该如何修改程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396612/

相关文章:

c - 将代码从 ATmega32 修改为 Arduino Mega - 函数 `main' 中出现错误,即使没有

c - 我的 IF 条件表现得很奇怪,HELP C

运行时在c源代码中编译另一个源代码

c++ - 在 C++ 中使用 C 库

c - "Inline C"- 问题

c - 带有 SIOCSIFFLAGS 的 setsockopt 和 ioctl 有什么区别?

c - 使出现巨大的数字

c - UART 接收中断启用但没有 ISR?

c - 在C标准库函数中如何确定返回char指针是否需要空闲?

c - 使用凯撒密码加密文本