c++ - 排序 : Is this performance difference for real or am I doing something wrong?

标签 c++ sorting

我需要对很多由 8 个 float 组成的小数组进行排序。最初我使用的是 std::sort 但对其性能不满意,我尝试了由此生成的比较交换算法:http://pages.ripco.net/~jgamble/nw.html

测试代码如下:

template <typename T>
bool PredDefault(const T &a, const T &b) {return a > b;}

template <typename T>
bool PredDefaultReverse(const T &a, const T &b) {return a < b;}

template <typename T>
void Sort8(T* Data, bool(*pred)(const T &a, const T &b) = PredDefault) {
    #define Cmp_Swap(a, b) if (pred(Data[a], Data[b])) {T tmp = Data[a]; Data[a] = Data[b]; Data[b] = tmp;}

    Cmp_Swap(0, 1); Cmp_Swap(2, 3); Cmp_Swap(4, 5); Cmp_Swap(6, 7);
    Cmp_Swap(0, 2); Cmp_Swap(1, 3); Cmp_Swap(4, 6); Cmp_Swap(5, 7);
    Cmp_Swap(1, 2); Cmp_Swap(5, 6); Cmp_Swap(0, 4); Cmp_Swap(3, 7); 
    Cmp_Swap(1, 5); Cmp_Swap(2, 6);  
    Cmp_Swap(1, 4); Cmp_Swap(3, 6);
    Cmp_Swap(2, 4); Cmp_Swap(3, 5);
    Cmp_Swap(3, 4);

}

int lastTick;
int tick() {
    int hold = lastTick;
    lastTick = GetTickCount();
    return lastTick - hold;
}

int main()
{
    vector<vector<float>> rVec(1000, vector<float>(8)); 
    for (auto &v : rVec) {
        v[0] = ((float)rand()) * 0.001;
        v[1] = ((float)rand()) * 0.001;
        v[2] = ((float)rand()) * 0.001;
        v[3] = ((float)rand()) * 0.001;
        v[4] = ((float)rand()) * 0.001;
        v[5] = ((float)rand()) * 0.001;
        v[6] = ((float)rand()) * 0.001;
        v[7] = ((float)rand()) * 0.001;
    }

    system("PAUSE");
    tick();

    for (int n = 0; n < 50000; n++)
    for (int j = 0; j < rVec.size(); j++) {
        std::sort(rVec[j].begin(), rVec[j].end(), PredDefault<float>);
        std::sort(rVec[j].begin(), rVec[j].end(), PredDefaultReverse<float>);
        //Sort8(rVec[j].data(), PredDefault<float>);
        //Sort8(rVec[j].data(), PredDefaultReverse<float>);
    }

    cout << "\nTime: " << tick() << "\n";
    system("PAUSE");

    return 1;
}

在测试一个或另一个时添加/删除评论标记。

我并没有期待太多,但差异是支持交换排序的 10 倍(测试在 vs2012 的发布配置中完成,关闭了节能功能)。结果也查出来了。这是正确的吗?

最佳答案

我可以马上想到几个原因。

  1. 您有硬编码比较。这有助于流水线化多条指令,从而使其非常高效。但想象一下将其编码为 N=1000。你必须写 1000*1000 个比较。
  2. std::sort 进行O(nlogn) 比较。但是这个大 O 符号适用于大 N,因为符号常数可以很大。所以你不能通过在 8 个值的范围内运行来判断效率。

关于c++ - 排序 : Is this performance difference for real or am I doing something wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28869451/

相关文章:

json - JQ排序键任意顺序

java - 如何在 Java 中实现无操作比较器?

c++ - 使用 ifstream 时,Visual Studio 2017 中 Release 和 Debug 的输出不同?

c++ - 输出错误 Project Euler 7

c++ - 如何移动到文件夹并执行 Windows 命令行调用

sorting - 有没有一种有效的方法来对 RethinkDB 中的联接结果进行排序?

c# - 排序字符串列表

java - 使用2个数组进行插入排序java

c++ - boost::geometry: 使用圆的最近邻

c++ - extern "C"(C联动)默认