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
, d
是0x0000
, 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/