简单的比较 C 语言下交换 a,b 数值的代码效率

以下几个语句都能交换a,b的值

1)

a^=b^=a^=b;

2)

temp = a;
a = b;
b = temp;

3)

a = a^b;
b = a^b;
a = a^b;

效率为2) > 3) > 1)

验证代码如下:(linux下GCC和win下codeblocks通过编译)

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

void speed_1()
{
    long i = 100000000;
    while(i){
        int a = 10;
        int b = 20;
        a^=b^=a^=b;
        i--;
    }
}

void speed_2()
{
    long i = 100000000;
    int temp = 0;
    while(i){
        int a = 10;
        int b = 20;
        temp = a;
        a = b;
        b =  temp;
        i--;
    }
}

void speed_3()
{
    long i = 100000000;
    while(i) {
        int a = 10;
        int b = 20;
        a = a^b;
        b = a^b;
        a = a^b;
        i--;
    }
}

int main(void)
{
    struct timeval start;
    struct timeval end;

    unsigned long diff_1;             //此处的1,2,3数字代表的代码与上面所列一致
    unsigned long diff_2;
    unsigned long diff_3;

    gettimeofday(&start, NULL);       //gettimeofday()是C语言获得精确时间函数
    speed_1();
    gettimeofday(&end, NULL);
    diff_1 = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;

    gettimeofday(&start, NULL);
    speed_2();
    gettimeofday(&end, NULL);
    diff_2 = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;

    gettimeofday(&start, NULL);
    speed_3();
    gettimeofday(&end, NULL);
    diff_3 = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;

    printf("time_1 = %ld\n", diff_1);
    printf("time_2 = %ld\n", diff_2);
    printf("time_3 = %ld\n", diff_3);

    return 0;
}

记得以前有人深入的分析过,我也不会,就简单的控制变量看下表面现象,看谁的效率更高些。

等以后在尝试从代码角度进行分析吧。