关于false aliasing的一些看法

来源:互联网 发布:网络借贷不还会坐牢吗 编辑:程序博客网 时间:2024/06/10 22:30

在网上看到一个很有趣的代码,如下:

int main(){    const int n = 100000;#ifdef ALLOCATE_SEPERATE    double *a1 = (double*)malloc(n * sizeof(double));    double *b1 = (double*)malloc(n * sizeof(double));    double *c1 = (double*)malloc(n * sizeof(double));    double *d1 = (double*)malloc(n * sizeof(double));#else    double *a1 = (double*)malloc(n * sizeof(double) * 4);    double *b1 = a1 + n;    double *c1 = b1 + n;    double *d1 = c1 + n;#endif    //  Zero the data to prevent any chance of denormals.    memset(a1,0,n * sizeof(double));    memset(b1,0,n * sizeof(double));    memset(c1,0,n * sizeof(double));    memset(d1,0,n * sizeof(double));    //  Print the addresses    cout << a1 << endl;    cout << b1 << endl;    cout << c1 << endl;    cout << d1 << endl;    clock_t start = clock();    int c = 0;    while (c++ < 10000){#if ONE_LOOP        for(int j=0;j<n;j++){            a1[j] += b1[j];            c1[j] += d1[j];        }#else        for(int j=0;j<n;j++){            a1[j] += b1[j];        }        for(int j=0;j<n;j++){            c1[j] += d1[j];        }#endif    }    clock_t end = clock();    cout << "seconds = " << (double)(end - start) / CLOCKS_PER_SEC << endl;    system("pause");    return 0;}

地址:

http://stackoverflow.com/questions/8547778/why-is-one-loop-so-much-slower-than-two-loops?answertab=votes#tab-top

运行的结果很有趣,时间差异很大。

#define ALLOCATE_SEPERATE#define ONE_LOOP00600020006D0020007A002000870020seconds = 6.206#define ALLOCATE_SEPERATE//#define ONE_LOOP005E0020006B00200078002000850020seconds = 2.116//#define ALLOCATE_SEPERATE#define ONE_LOOP0057002000633520006F6A20007B9F20seconds = 1.894//#define ALLOCATE_SEPERATE//#define ONE_LOOP008C00200098352000A46A2000B09F20seconds = 1.993

这是一个关于false aliasing的问题,有这么几个链接可参考。先mark着,这几天好好研究研究。
什么是false aliasing:https://www.quora.com/Computer-Memory/What-is-false-aliasing
http://www.realworldtech.com/merom/8/
c++中如何处理或预防:
https://msdn.microsoft.com/en-us/library/5ft82fed.aspx

0 0