实验结果:
stl sort cost 18.75 seconds
c qsort cost 42 seconds
分析:
当然是因为qsort使用回调函数.
源代码(标准c/c++):
//use stl
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
//use c qsort
#include <cstdlib>
//clock
#include <ctime>
struct mytype{
int key;
int data;
};
struct mygen{
//typedef
mytype operator() (void) const {
mytype v;
v.key=rand();
return v;
}
};
struct stl_cmp:public binary_function<mytype,mytype,bool>{
bool operator() (const mytype& e1,const mytype& e2) const { return e1.key<e2.
key; }
};
static int qsort_cmp(const void* e1,const void* e2)
{
return (*(mytype*)e1).key-(*(mytype*)e2).key;
}
mytype a[10000000];
int main(int argc, char* argv[])
{
//stl sort
clock_t t;
generate(a, a+sizeof(a)/sizeof(a[0]), mygen());
t=clock();
sort(a,a+sizeof(a)/sizeof(a[0]),stl_cmp());
t=clock()-t;
cout<<"stl sort cost "<<t*1.0/CLK_TCK<<" seconds"<<endl;
//c qsort
generate(a, a+sizeof(a)/sizeof(a[0]), mygen());
t=clock();
qsort((void*)a,sizeof(a)/sizeof(a[0]),sizeof(a[0]),qsort_cmp);
t=clock()-t;
cout<<"c qsort cost "<<t*1.0/CLK_TCK<<" seconds"<<endl;
return 0;
}