据说CSDN有点高手,那么深入理解omp cache line问题的进来比划比划了
先看小程序:
/*------------------------------------------------------
int a[4],b[4],c[4],d[4];
int global[16];
for(int i=0;i<16;i++)
global[i]=1;
for(int i=0;i<4;i++)
{
a[i]=global[i];
b[i]=global[4+i];
c[i]=global[8+i];
d[i]=global[12+i];
}
//////////////////////////////parallel
#pragma omp parallel sections
{
#pragma omp section
{
double startwtime,endwtime;
startwtime=MPI_Wtime();
for (int i = 0; i < 5000000; i++)
{
int m=0;
for(int j=1;j<4;j++)
a[0]+=a[j];
}
}
#pragma omp section
{
double startwtime,endwtime;
startwtime=MPI_Wtime();
for (int i = 0; i < 5000000; i++)
{
int a=0;
for(int j=0;j<4;j++)
b[0]+=b[j];
}
}
#pragma omp section
{
double startwtime,endwtime;
startwtime=MPI_Wtime();
for (int i = 0; i < 5000000; i++)
{
int a=0;
for(int j=0;j<4;j++)
c[0]+=c[j];
}
}
#pragma omp section
{
double startwtime,endwtime;
startwtime=MPI_Wtime();
for (int i = 0; i < 5000000; i++)
{
int a=0;
for(int j=1;j<4;j++)
d[0]+=d[j];
}
}
}
}
***************************************************************************/
上述代码由于分别a,b,c,d四个数组落在同一cache line,所以并行时间比串行更慢的多。
但为什么把上述代码中的int a[4],b[4],c[4],d[4];换为
int *a = new int[4];
int *b = new int[4];
int *c = new int[4];
int *d = new int[4];
就可以正确并行呢?
在栈中和在堆中定义的变量在拷入cache时有什么区别?
有理解而且能说清楚的人吗