Your code is fast – if you're lucky

Your code is fast – if you’re lucky

你的代码很快——如果你足够幸运的话

Your code is fast - if you’re lucky. Recently, while I was working on an optimized Quicksort implementation, I came across a rather interesting quirk. Modern compilers (especially Clang) optimize loops using fast, branch-free instructions - provided you use the right programming style.

你的代码很快——如果你足够幸运的话。最近,在编写一个优化的快速排序(Quicksort)实现时,我偶然发现了一个相当有趣的特性。现代编译器(尤其是 Clang)会利用快速的无分支指令来优化循环——前提是你使用了正确的编程风格。


sort.h - a quicksort with sorting networks

sort.h - 基于排序网络的快速排序

// SPDX-License-Identifier: MIT
// sort.h - Branchless Quicksort
// (c) christof.kaser@gmail.com

#ifndef SORT_H
#define SORT_H

#ifndef BLQS_CMP
#define BLQS_CMP(a, b) ((a) < (b))
#endif

#include <stddef.h>
#include <string.h>

#define min(a, b) (((a) < (b)) ? (a) : (b))
#define SMALLPART 1024
#define SWSZ 512
#define UNROLL 16

#define sort2(a, b) do { \
    unsigned m = BLQS_CMP(a, b); \
    BLQS_TYPE x = a; \
    a = m ? a : b; \
    b = m ? b : x; \
} while(0)

// ... (The provided C code continues with sorting network macros and partition logic)
// ...(此处省略后续的排序网络宏定义及分区逻辑代码)