A C++ Quicksort Faster Than std::sort

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

A C++ Quicksort Faster Than std::sort

A C++ Quicksort Faster Than std::sort blqsort is a very fast quicksort algorithm. I am not aware of any other general-purpose comparison-based sorting algorithm that is faster on random data. Only specialized SIMD-based algorithms are generally faster when dealing with small primitive data types.

blqsort 是一个非常快速的快速排序算法。据我所知,在处理随机数据时,没有其他通用的基于比较的排序算法比它更快。只有在处理小型原始数据类型时,专门的基于 SIMD 的算法通常才会更快。

blqsort The main ideas are branchless partitioning, sorting networks for small partitions and robust pivot selection. The implementation is available on GitHub under the MIT license. There is also a C version of it, including multithreaded versions, each as a single header file.

blqsort 的主要思想是无分支分区、针对小分区的排序网络以及稳健的枢轴选择。该实现可在 GitHub 上以 MIT 许可证获取。它还有一个 C 语言版本,包括多线程版本,每个版本都是一个单独的头文件。

blqsort on Github The following benchmarks show the execution times for sorting 50 million random doubles using different sorting implementations. The measurements were taken on an Apple M1 system using Clang and on an Intel i5-9300H Linux system using GCC, both compiled with the -O3 option.

blqsort on Github 以下基准测试显示了使用不同排序实现对 5000 万个随机双精度浮点数进行排序的执行时间。测量是在使用 Clang 的 Apple M1 系统和使用 GCC 的 Intel i5-9300H Linux 系统上进行的,两者均使用 -O3 选项编译。

Implementation Apple M1 Intel i5-9300H std::sort 1.33s 4.97s ipnsort ClickHouse C++ port 0.99s 2.31s blqsort 0.67s 1.33s For a fair comparison, the single-threaded version of blqs was used here. On the M1, the multithreaded versions are roughly another factor of 3 faster. In terms of runtime, the C versions differ only very little from the C++ version.

实现 Apple M1 Intel i5-9300H std::sort 1.33s 4.97s ipnsort ClickHouse C++ port 0.99s 2.31s blqsort 0.67s 1.33s 为了公平比较,这里使用了 blqs 的单线程版本。在 M1 上,多线程版本大约快了 3 倍。在运行时间方面,C 版本与 C++ 版本几乎没有区别。

Execution times for sorting 50 million of these structs with random id values. struct entry { int id; int value; bool operator<(const entry& other) const { return id < other.id; } }; struct entry data[SIZE]; blqs::sort(data, data + SIZE);

对 5000 万个具有随机 id 值的结构体进行排序的执行时间。struct entry { int id; int value; bool operator<(const entry& other) const { return id < other.id; } }; struct entry data[SIZE]; blqs::sort(data, data + SIZE);

Implementation Apple M1 Intel i5 std::sort 3.45s 4.10s ipnsort ClickHouse C++ port 0.98s 2.63s blqsort 0.75s 1.40s Already sorted and reverse-sorted inputs are detected and handled efficiently. Inputs with many duplicate keys are optimized as well.

实现 Apple M1 Intel i5 std::sort 3.45s 4.10s ipnsort ClickHouse C++ port 0.98s 2.63s blqsort 0.75s 1.40s 已经排序和反向排序的输入会被检测并高效处理。具有许多重复键的输入也会得到优化。

From Basic Quicksort to a Fast Branchless Implementation The execution times, unless otherwise specified, apply to an Apple M1 system. A small, elegant, recursive quicksort:

从基础快速排序到快速无分支实现:除非另有说明,否则执行时间适用于 Apple M1 系统。一个小型、优雅的递归快速排序:

#include #include #include constexpr int SIZE = 50000000; double data[SIZE]; double time() { static auto time0 = std::chrono::high_resolution_clock::now(); auto t = std::chrono::high_resolution_clock::now(); std::chrono::duration diff = t - time0; return diff.count(); } void sortq(double ar[], int len) { if (len < 2) return; double piv = ar[0]; int mid = 0; for (int i = 1; i < len; i++) { if (ar[i] < piv) { mid += 1; std::swap(ar[mid], ar[i]); } } std::swap(ar[mid], ar[0]); sortq(ar + mid + 1, len - mid - 1); sortq(ar, mid); } int main() { double t0; printf(“Sorting %d million doubles\n”, SIZE / 1000000); for (int i = 0; i < SIZE; i++) data[i] = rand() / 1024.0; t0 = time(); sortq(data, SIZE); printf(“sortq: %.2fs\n”, time() - t0); }

(代码块保持原样)

c++ -O1 main.cpp && ./a.out Sorting 50 million doubles sortq: 4.61s If you sort the sorted data again, all elements in the partition are greater than or equal to the pivot element. The second partition becomes only one element smaller each time, and the function is called recursively millions of times, which leads to a stack overflow after a few hours.

c++ -O1 main.cpp && ./a.out 排序 5000 万个双精度浮点数 sortq: 4.61s 如果再次对已排序的数据进行排序,分区中的所有元素都将大于或等于枢轴元素。第二个分区每次只减少一个元素,函数被递归调用数百万次,这会在几个小时后导致堆栈溢出。

You can prevent this with tail call elimination. That is, the first recursive call remains, while the second is replaced by a loop iteration. You now need to ensure that the smaller partition is called recursively. So swap them if necessary.

你可以通过尾调用消除来防止这种情况。也就是说,保留第一个递归调用,而将第二个替换为循环迭代。现在你需要确保较小的分区被递归调用。因此,必要时交换它们。

void sortq(double* ar, int len) { while (len >= 2) { double piv = ar[0]; int mid = 0; for (int i = 1; i < len; i++) { if (ar[i] < piv) { mid += 1; std::swap(ar[mid], ar[i]); } } std::swap(ar[mid], ar[0]); double* ar2 = ar + mid + 1; int len2 = len - mid - 1; len = mid; if (len2 > len) { std::swap(len, len2); std::swap(ar, ar2); } sortq(ar2, len2); } }

(代码块保持原样)

Now the program no longer crashes, but it will take a few days to finish. Because of this unfavorable partitioning, the worst-case scenario of O(N²) has become a reality. However, insertion sort would not make it any faster either. Let’s just use the middle element as the pivot - then the problem of sorting already sorted data will be gone.

现在程序不再崩溃,但需要几天时间才能完成。由于这种不利的分区,O(N²) 的最坏情况已成为现实。然而,插入排序也不会让它变得更快。让我们直接使用中间元素作为枢轴——这样排序已排序数据的问题就会消失。

. while (len >= 2) { std::swap(ar[len / 2], ar[0]); double piv = ar[0]; . The only remaining risk is that someone intentionally sends specially crafted data to trigger this behavior. To eliminate this threat, the pivot point should be selected randomly. This implementation is sufficient for many purposes and is also reasonably fast. By the way, “Lomuto” partitioning is used here. “Hoare” partitioning performs fewer comparisons and swaps, but on modern CPUs its cache behavior can be less favorable.

. while (len >= 2) { std::swap(ar[len / 2], ar[0]); double piv = ar[0]; . 唯一剩下的风险是有人故意发送特制数据来触发这种行为。为了消除这种威胁,应该随机选择枢轴点。这种实现对于许多用途来说已经足够,而且速度也相当快。顺便说一句,这里使用了“Lomuto”分区。“Hoare”分区执行的比较和交换较少,但在现代 CPU 上,其缓存行为可能不太理想。

But why write your own implementation when std::sort exists? . #include . . t0 = time(); std::sort(data, data + SIZE); printf(“std::sort: %.2fs\n”, time() - t0); . std::sort: 1.31s That’s on ARM Mac - on a x86 system, std::sort is only about 10% faster. How can you make a quicksort run faster than std::sort?

但是,既然有 std::sort,为什么要自己写实现呢?. #include . . t0 = time(); std::sort(data, data + SIZE); printf(“std::sort: %.2fs\n”, time() - t0); . std::sort: 1.31s 这是在 ARM Mac 上的结果——在 x86 系统上,std::sort 仅快约 10%。如何让快速排序比 std::sort 运行得更快?

Sorting networks For partitions with up to about 20 elements, insertion sort is faster than quicksort. But there is something even faster for small partitions: sorting networks. Each partition size is handled in its own program branch. For a partition size of two, the two elements are simply compared and swapped if necessary. However, as the number of elements increases, the logic becomes increasingly complex.

排序网络:对于最多约 20 个元素的分区,插入排序比快速排序更快。但对于小分区,还有更快的方案:排序网络。每个分区大小都在其自己的程序分支中处理。对于大小为 2 的分区,只需比较这两个元素并在必要时进行交换。然而,随着元素数量的增加,逻辑变得越来越复杂。

inline void sort2(double& a, double& b) { if (a < b) std::swap(a, b); } inline void sort3(double& a, double& b, double& c) { sort2(a, b); sort2(b, c); sort2(a, b); } inline void sort4(double& a, double& b, double& c, double& d) { sort2(a, b); sort2(c, d); sort2(a, c); sort2(b, d); sort2(b, c); } inline void sort5(double& a, double& b, double& c, double& d, double& e) { sort2(b, c); sort2(d, e); sort2(b, d); sort2(a, c); sort2(a, d); sort2(c, e); sort2(a, b); sort2(c, d); sort2(b, c); } . while (len >= 6) { . . } if (len == 5) sort5(ar[0], ar[1], ar[2], ar[3], ar[4]); else if (len == 4) sort4(ar[0], ar[1], ar[2], ar[3]); else if (len == 3) sort3(ar[0], ar[1], ar[2]); else if (len == 2) sort2(ar[0], ar[1]); }

(代码块保持原样)

When if slows you down, avoid it Let’s consider a simple task: Iterate through an

当 if 语句拖慢你的速度时,请避免使用它。让我们考虑一个简单的任务:遍历一个