关于false aliasing的一些看法

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

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#else
        for(int j=0;jfor(int j=0;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_LOOP
00600020
006D0020
007A0020
00870020
seconds = 6.206

#define ALLOCATE_SEPERATE
//#define ONE_LOOP
005E0020
006B0020
00780020
00850020
seconds = 2.116

//#define ALLOCATE_SEPERATE
#define ONE_LOOP
00570020
00633520
006F6A20
007B9F20
seconds = 1.894

//#define ALLOCATE_SEPERATE
//#define ONE_LOOP
008C0020
00983520
00A46A20
00B09F20
seconds = 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

你可能感兴趣的:(thinking,in,c++)