几种交换方式与参数传递方式效率的比较,发现STL最慢
/*Copyright (c) 2007,九天雁翎
* All rights reserved.
* 几种交换方式与参数传递方式效率的比较
* 完成日期:2007年7月7日*/
#include "stdafx.h"
#include "myself.h"
#include <iostream>
#include <utility>
using namespace std;
const int RUNTIME = 1e5;
void swap1(int &v1, int &v2);
void swap2(int &v1, int &v2);
void swap3(int *p1, int *p2);
int main()
{
int v1 = 10000;
int v2 = 20000;
double t1 = myself::getTime();
for (int i = 0; i < RUNTIME; ++i)
{
swap1(v1,v2);
}
double t2 = myself::getTime() - t1;
cout <<v1 <<'/t' <<v2 <<endl;
cout <<"Reference pass parameter and bit^ way used time: "<<t2 <<endl;
t1 = myself::getTime();
for (int i = 0; i < RUNTIME; ++i)
{
swap2(v1,v2);
}
t2 = myself::getTime() - t1;
cout <<v1 <<'/t' <<v2 <<endl;
cout <<"Reference pass parameter way used time: "<<t2 <<endl;
t1 = myself::getTime();
for (int i = 0; i < RUNTIME; ++i)
{
swap3(&v1,&v2);
}
t2 = myself::getTime() - t1;
cout <<v1 <<'/t' <<v2 <<endl;
cout <<"Point pass parameter way used time:" <<t2 <<endl;
for (int i = 0; i < RUNTIME; ++i)
{
swap(v1,v2);
}
t2 = myself::getTime() - t1;
cout <<v1 <<'/t' <<v2 <<endl;
cout <<"STL way used time: " <<t2 <<endl;
return 0;
}
void swap1(int &v1, int &v2)
{
v1 = v1^v2;
v2 = v1^v2;
v1 = v1^v2;
}
void swap2(int &v1, int &v2)
{
int temp = v1;
v1 = v2;
v2 = temp;
}
void swap3(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
结果是,指针效率一般最快,STL最慢,按位或没有效率优势,你可以改变RUNTIME去试试不同结果
Posted By 九天雁翎 at 九天雁翎的博客 on 2007年07月07日