排序性能

147 阅读1分钟

这几天看算法竞赛入门经典第二版的习题解答,第一章介绍了几种排序方式的性能,自测了一下。

#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
#define _for(i,a,b) for(int i=(a);i<(b);++i)
const int N=1000000;
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  getData(){
    _for(i, 0, N) {
        tss[i].a = rand();
        tss[i].b = rand();
        tss[i].c = rand();
    }
}
int main() {
    srand(time(NULL));
    getData();
    clock_t start = clock();
    std::sort(tss, tss + N, cmp);
    printf("sort by functon pointer : %ld\n", clock() - start);

    getData();
    start = clock();
    std::sort(tss, tss + N, cmpFunctor());
    printf("sort by functor : %ld\n", clock() - start);

    getData();
    start = clock();
    qsort(tss, N, sizeof(TS), cmp4qsort);
    printf("qsort by function pointer : %ld\n", clock() - start);

    return 0;
}

结局是这样的,qsort是最快的,反而functor是最慢的。 多次实验之后确认,qsort确实最快,其余两个不一定。

image.png