赞
踩
1.1.1 排序性能问题
C语言的函数qsort,C++中的sort(直接传入排序函数)以及传入functor对象的sort函数代码以及时间。
- #include<bits/stdc++.h>
- using namespace std;
- #define _for(i,a,b) for( int i=(a); i<(b); ++i)
- const int N = 10000000;
- struct TS{
- int a,b,c;
- };
- inline bool cmp (const TS&t1, const TS&t2){
- if(t1.a!=t2.a)return t1.a<t2.a;
- if(t1.b!=t2.b)return t1.b<t2.b;
- return t1.c<t2.c;
- }
-
- int cmp4qsort(const void * a, const void * b){
- TS *t1 = (TS*)a, *t2 = (TS*)b;
- if(t1->a != t2->a) return t1->a - t2->a;
- if(t1->b != t2->b) return t1->b - t2->b;
- return t1->c - t2->c;
- }
- struct cmpFunctor{
- inline bool operator() (const TS& t1, const TS& t2){
- if(t1.a != t2.a) return t1.a < t2.a;
- if(t1.b != t2.b) return t1.b < t2.b;
- return t1.c < t2.c;
- }
- };
-
- TS tss[N];
-
- void genData(){
- _for(i , 0, N){
- tss[i].a = rand();
- tss[i].b = rand();
- tss[i].c = rand();
- }
- }
-
- int main()
- {
- srand(time(NULL));
-
- genData();
- clock_t start = clock();
- sort(tss, tss+N, cmp);
- printf("sort by funtion pointer : %ld\n",clock() - start);
-
- genData();
- start = clock();
- sort(tss, tss+N, cmpFunctor());
- printf("sort by functor : %ld\n",clock() - start);
-
- genData();
- start = clock();
- qsort(tss, N, sizeof(TS), cmp4qsort);
- printf("qso
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。