swap:临时变量vs和交换vs位运算 时间对比

时间:2021-04-23 21:24:46

/*1 编写一个函数,不用临时变量,直接交换两个数*/
void swap0(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swap1(int* a, int* b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
void swap2(int *a, int* b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
#include "time.h"
#include "iostream"
int main()
{
clock_t t0;
clock_t t1;
int a = 1;
int b = 2;

t0 = clock();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 100; j++)
swap0(&a, &b);
}
t1 = clock();

std::cout << "swap0(): " << t1 - t0 << "ms" << std::endl;

t0 = clock();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 100; j++)
swap1(&a, &b);
}
t1 = clock();
std::cout << "swap1(): " << t1 - t0 << "ms" << std::endl;

t0 = clock();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 100; j++)
swap2(&a, &b);
}
t1 = clock();
std::cout << "swap2(): " << t1 - t0 << "ms" << std::endl;

return 0;
}

实验结果:

swap0(): 30ms
swap1(): 34ms
swap2(): 27ms

实验标明:速度 位运算>临时变量>和运算。

分析:和运算里用到了加减操作,所以会比临时变量慢。