跳到正文

个人记录

时间常数的一些测试记录

Autre约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年3月8日
收录
2026年8月23日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

代码头:

C++
#include<algorithm>
#include<iostream>
unsigned inline rd() {
    static unsigned x;
    x ^= x << 16;
    x ^= x >> 5;
    x ^= x << 1;
    return x;
}

struct 单关键字排序

struct 直接排序

C++
struct A{unsigned a, b;}t[N];
int main() { unsigned sm = 0;
    for (int i=0; i<N; i++) t[i] = {rd(), rd()};
    std::sort(t, t+N, [](A x, A y){return x.a<y.a;});
    for (int i=0; i<N; i++) sm += (t[i].a^i)+(t[i].b^~i);
    printf("%u", sm);
}
  • 二元 struct:1.723s,N=1×108N=1\times10^8
  • 四元 struct:3.083s,N=1×108N=1\times10^8
  • 八元 struct:2.769s,N=5×107N=5\times10^7

优点:访存连续

备注:用以比较的 lambda 被内联优化掉了,所以 lambda 的参数参数是否使用引用没有差距。

对索引排序,结构体存储

C++
struct A{unsigned a, b;}t[N];
int o[N];
int main() { unsigned sm = 0;
    for (int i=0; i<N; i++) t[i] = {rd(), rd()}, o[i] = i;
    std::sort(o, o+N, [](int i, int j){return t[i].a<t[j].a;});
    for (int i=0; i<N; i++) sm += (t[o[i]].a^i)+(t[o[i]].b^~i);
    printf("%u", sm);
}

缺点:比较函数内部访存不连续。

  • 二元 struct:2.418s,N=1×108N=1\times10^8
  • 四元 struct:6.037s,N=1×108N=1\times10^8
  • 八元 struct:3.489s,N=5×107N=5\times10^7

对索引排序,数组存储

C++
int a[N], b[N], o[N];
int main() { unsigned sm = 0;
    for (int i=0; i<N; i++) a[i] = rd(), b[i] = rd(), o[i] = i;
    std::sort(o, o+N, [](int x, int y){return a[x]<a[y];});
    for (int i=0; i<N; i++) sm += (a[o[i]]^i)+(b[o[i]]^~i);
    printf("%u", sm);
}
  • 二元 struct:1.931s,N=1×108N=1\times10^8
  • 四元 struct:2.816s,N=1×108N=1\times10^8
  • 八元 struct:2.085s,N=5×107N=5\times10^7

优点:不需要大量数据移动。

总结

二元时结构体排序快,三元及以上时索引排序、数组存储快。

原文