我想测试 C++ 中按值传递和按引用传递的速度:
class MyAddress{
char *name;
long int number;
char *street;
char *town;
char state[2];
long zip;
std::vector<int> v_int;
public:
MyAddress(int i){
v_int.resize(1000000);
std::fill(v_int.begin(),v_int.end(),i);
}
MyAddress& assign1(MyAddress const& x)
{
MyAddress tmp(x); // copy construction of tmp does the hard work
std::swap(*this, tmp); // trade our resources for tmp's
return *this; // our (old) resources get destroyed with tmp
}
MyAddress& assign2(MyAddress x)//x is a copy of the source
{ //hard work already done
std::swap(*this, x); // trade our resources for x's
return *this; // our (old) resources get destroyed with x
}
void f1(MyAddress v){int i=v.v_int[3];}
void f2(MyAddress const &ref){int i=ref.v_int[3];}
};
MyAddress get_names(MyAddress& ref){return ref;}
主要的:
int _tmain(int argc, _TCHAR* argv[])
{
float time_elapsed1=0;
float time_elapsed2=0;
for(int i=0;i<100;i++){
{
MyAddress a1(1);
MyAddress a2(2);
MyAddress a3(3);
clock_t tstart=std::clock();
a1.f1(a2);
a1.f1(a3);
clock_t tend=std::clock();
time_elapsed1+=((float)tend-(float)tstart);
}
{
MyAddress a1(1);
MyAddress a2(2);
MyAddress a3(3);
clock_t tstart=std::clock();
a1.f2(a2);
a1.f2(a3);
clock_t tend=std::clock();
time_elapsed2+=((float)tend-(float)tstart);
}
}
std::cout<<std::fixed<<"\nassign1 time elapsed : "
<<time_elapsed1/CLOCKS_PER_SEC;
std::cout<<std::fixed<<"\nassign2 time elapsed : "
<<time_elapsed2/CLOCKS_PER_SEC;
system("pause");
return 0;
}
时差结果令人震惊:
分配1时间过去:81.044998
assign2 已用时间:0.002000
它是否正确?
“按价值”的速度怎么能比“按参考”高得多?