Volatile关键字

来源:互联网 发布:mysql insert出错 编辑:程序博客网 时间:2024/05/16 06:25

Volatile关键字

老大要我测下几个基本运算在android设备上的性能,很简单,产生一些随机数据,重复的计算下。代码如下:

测试代码

static void testCalculationPerformance(){    struct timeval start, end;    int i;    short temShort;    int temInt;    float temFloat;    double temDouble;    int *intA, *intB;    float *floatA, *floatB;    double *doubleA, *doubleB;    short *shortA;    if (        (intA = (int*)malloc(100000 * sizeof(int))) &&        (intB = (int*)malloc(100000 * sizeof(int))) &&        (floatA = (float*)malloc(100000 * sizeof(float))) &&        (floatB = (float*)malloc(100000 * sizeof(float))) &&        (doubleA = (double*)malloc(100000 * sizeof(double))) &&        (doubleB = (double*)malloc(100000 * sizeof(double))) &&        (shortA = (short*)malloc(100000 * sizeof(short)))        );    else    {        CQ_ERROR("Memory alloc failed", __LINE__);        return;    }    /***************************************    *** Generate the random data sample ****    ***************************************/    srand(SEEDS1);    for (i = 0; i < 100000; i++){        intA[i] = rand();        shortA[i] = (short)intA[i];        while( (temInt = rand()) == 0);        intB[i] = temInt;       }    srand(SEEDS1);    for (i = 0; i < 100000; i++){        floatA[i] = (float)rand() + ((float)rand()/100000);        floatB[i] = (float)rand() + ((float)rand()/100000);    }    srand(SEEDS1);    for (i = 0; i < 100000; i++){        doubleA[i] = (float)rand() + ((float)rand()/100000);        doubleB[i] = (float)rand() + ((float)rand()/100000);    }    /**************************    ******* int test **********    **************************/    ...    /**************************    ******* atan test *********    **************************/    gettimeofday(&start, NULL);    for (i = 0; i < 100000; i++){        temShort = Math_atan(intA[i],intB[i]);    }    gettimeofday(&end, NULL);    LOGD("CalculationTest:Math_atan time %u", end.tv_usec - start.tv_usec);    ...    free process ...;    return;}

相信各位已经可以看出来,这段代码在release模式下没有有效输出,测试部分for循环被编译器优化掉了(给老大看了一眼老大就说你这代码没有有效输出直接被编译器优化掉,是在release模式下?==),在release模式下测了一遍,结果gg,每个测试用时只有1微秒。

回头找解决方法,想到两点:

1. for循环的优化往往是用寄存器来代替内存处理临时变量,代码中的temInt等。2. C++中的volatile关键字会强制线程前往内存中对数据进行读取。

加了volatile关键字,结果测试perfect。

测试结果:

测试说明:1. 每个测试进行了100000次。2. 测试设备魅族Note2(CPU:1.3GHz,8Cores,MTK MT6753)  
data type Operation type TesultRes(microsecond) int add 514 int sub 525 int mul 668 int div 2445 float add 3104 float sub 4018 float mul 2074 float div 6650 double add 4771 double sub 5436 double mul 4023 double div 30360 – atanf 2376 – atan 11041 – sinf 50447 – sin 93261 – cosf 50673 – cos 78917

未完待续

。。。
0 0
原创粉丝点击