在网上看代码,偶然间发现了swap()的另一种写法,利用了位运算,不是很好理解——至少不如朴素的swap()那么直接。
作为OIer,效率至上,我便对比了朴素swap()和“神奇”swap()的效率。
测试代码如下。
/*
* swap() test
* mike-w
* 2012-4-14
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define AUTO_TEST
int f[2];
int swap1(int *e1, int *e2)
{
int tmp=*e1;
*e1=*e2;
*e2=tmp;
return 0;
}
int swap2(int *e1, int *e2)
{
(*e1)^=(*e2)^=(*e1)^=(*e2);
return 0;
}
int measure(clock_t start, clock_t end)
{
printf("time cost= %.5f secs.\n",
(float)(end-start)/(float)CLOCKS_PER_SEC);
return 0;
}
int test(__int64 count)
{
clock_t start,end;
__int64 i;
printf("==>call swap() %I64d times\n",count);
puts("swap() version 1:");
start=clock();
for(i=0;i<count;i++)
swap1(f,f+1);
end=clock();
measure(start,end);
puts("swap() version 2:");
start=clock();
for(i=0;i<count;i++)
swap2(f,f+1);
end=clock();
measure(start,end);
return 0;
}
int main(void)
{
#ifdef USER_INPUT
__int64 count;
puts("swap for how many times?");
scanf("%I64d",&count);
test(count);
#endif
#ifdef AUTO_TEST
__int64 i;
for(i=100;i<=10000000000;i*=10)
test(i);
#endif
return 0;
}
结果在这里,由于我的忍耐力有限,所以没有等待测试程序运行完便ctrl+c终止——否则我不知道要等几千年==!
==>call swap() 100 times
swap() version 1:
time cost= 0.00000 secs.
swap() version 2:
time cost= 0.00000 secs.
==>call swap() 1000 times
swap() version 1:
time cost= 0.00000 secs.
swap() version 2:
time cost= 0.00000 secs.
==>call swap() 10000 times
swap() version 1:
time cost= 0.00000 secs.
swap() version 2:
time cost= 0.00100 secs.
==>call swap() 100000 times
swap() version 1:
time cost= 0.00200 secs.
swap() version 2:
time cost= 0.00400 secs.
==>call swap() 1000000 times
swap() version 1:
time cost= 0.02700 secs.
swap() version 2:
time cost= 0.03600 secs.
==>call swap() 10000000 times
swap() version 1:
time cost= 0.27200 secs.
swap() version 2:
time cost= 0.35300 secs.
==>call swap() 100000000 times
swap() version 1:
time cost= 2.35400 secs.
swap() version 2:
time cost= 3.26200 secs.
==>call swap() 1000000000 times
swap() version 1:
time cost= 24.65700 secs.
swap() version 2:
time cost= 32.16100 secs.
==>call swap() 10000000000 times
swap() version 1: