某本不知道知不知名的算法书里说:仿函数传到sort的自定义比较函数是最快的,其次是qsort,其次是普通函数传比较函数。
本人不信,所以自己测试了一下,发现qsort是最快的,甚至比传普通函数的快5倍。还有传仿函数的sort比默认比较还快。
所以有人知道为什么吗?
测试代码:
#include<bits/extc++.h>
using namespace std;
using namespace chrono;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
#define _FF(_Name,_Begin,_End) for(auto _Name=(_Begin);_Name<(_End);_Name++)
mt19937_64 __Random_Number__(system_clock::now().time_since_epoch().count());
uniform_int_distribution<uint> __Random_Dist__(0,INT_MAX);
#define rand() __Random_Dist__(__Random_Number__)
#define srand(__X) __Random_Number__.seed(__X)
#endif
struct stu{
int a,b,c;
bool operator>(const stu& b)const{
return this->a==b.a?this->b==b.b?this->c>b.c:this->b>b.b:this->a>b.a;
}
bool operator<(const stu& b)const{
return this->a==b.a?this->b==b.b?this->c<b.c:this->b<b.b:this->a<b.a;
}
}a[5][3000000];
void init(){
_FF(i,0,5){
_FE(a[i],&j){
j={rand(),rand(),rand()};
}
}
}
struct cmp0{
bool operator()(const stu& a,const stu& b){
return a>b;
}
};
bool cmp1(const stu& a,const stu& b){
return a>b;
}
int cmp2(const void *a,const void *b){
stu *x=(stu*)(a),*y=(stu*)(b);
return *x>*y;
}
double t1,t2,t3,t4,t5;
auto be=system_clock::now().time_since_epoch();
void beg(){
be=system_clock::now().time_since_epoch();
}
void ed(double &t){
t=duration_cast<milliseconds>(system_clock::now().time_since_epoch()-be).count();
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
while(1){
init();
beg();
sort(a[0],a[0]+3000000,cmp0());
ed(t1);
beg();
sort(a[1],a[1]+3000000,cmp1);
ed(t2);
beg();
qsort(a[2],3000000,sizeof(stu),cmp2);
ed(t3);
beg();
sort(a[3],a[3]+3000000,greater<>());
ed(t4);
beg();
sort(a[4],a[4]+3000000);
ed(t5);
cout<<t1<<' '<<t2<<' '<<t3<<' '<<t4<<' '<<t5<<endl;
system("pause");
}
return 0;
}