English | 한국어
A C++20 experiment in small-block sorting, boundary trimming, and tiled merging. The initial study compares four custom sorting variants (Ideas 1–4) with std::sort, std::stable_sort, and a basic Quicksort on synthetic, game-inspired workloads, with subsequent follow-up experiments (Idea 5+) explored separately.
The focus is on 4-byte integer keys and 8-byte key + entity ID records. This is a learning project with workload-dependent results, not a general-purpose replacement for the standard library.
AI collaboration
I am an undergraduate studying algorithms and computer architecture. I heavily relied on ChatGPT and Gemini to implement the C++20 code, explore low-level optimizations, and build the benchmark/profiling tools. The initial hypotheses came from my own questions while studying sorting. That describes how the project started, not a claim that these techniques are new.
- Motivation
- Build and run
- How the four ideas evolved
- Follow-up ideas (Idea 5+)
- Workloads
- Recorded results
- Benchmark methodology and reproduction
- Scope and limitations
- Repository guide
- Feedback and contributions
While studying sorting algorithms, I wondered: Quicksort has an O(N²) worst case and the same O(N log N) average complexity as Heapsort or Mergesort. Why can it be faster in practice?
Memory access patterns, comparison and movement costs, branch behavior, and implementation details all matter. That led to two questions:
- Would switching to insertion sort at a 64-byte leaf size reduce the overhead of sorting tiny partitions?
- Could partition statistics or searches outward from a merge boundary reduce unnecessary work?
The implementation uses a fixed 64-byte leaf budget and 8 KiB tiles. A leaf therefore contains 16 int32_t keys or 8 records. These sizes are tuning choices: a 64-byte range is not necessarily cache-line aligned, and its size does not guarantee an L1 hit or cache residency.
Requirements: a C++20-capable g++, GNU Make, and a shell. Run from the repository root:
git clone https://github.com/Janbyeol/cache-aware-sort.git
cd cache-aware-sort
# Build and run correctness tests for both item formats.
make -f makefile.txt test
# Build all four test/benchmark executables.
make -f makefile.txt all
# Run the wall-clock benchmark for both formats.
make -f makefile.txt benchUse -f makefile.txt. The default build flags are -O3 -std=c++20 -Wall -Wextra -Iinclude.
test_4b/test_8b: correctness checks. The suite covers boundary sizes, all seven workloads, randomized cases, record integrity, allocation overflow, and additional boundary-trimmed merge regressions.bench_4b/bench_8b: fixed-size wall-clock benchmark runners. They writekey_only_4b_summary.csvandkey_id_8b_summary.csvin the working directory.make -f makefile.txt benchruns the complete suite, not a single-size benchmark. Use the platform profiling scripts below to chooseN.
With Visual Studio C++ build tools and a Windows SDK installed:
.\generate_solution.batOpen the generated cache-aware-sort.sln, select Release | x64, and build. The solution contains test_4b, test_8b, bench_4b, and bench_8b; executables are written to bin\Release\.
.\bin\Release\test_4b.exe
.\bin\Release\test_8b.exeThe solution builds x64 executables with an SSE2 baseline. Use the separate Windows ARM64 profiling scripts below for native ARM64 builds.
The initial implementation explored four ideas sharing the item types and low-level helpers in include/hybrid_sorts.hpp.
cache_leaf_quick uses median-of-three Hoare partitioning, then switches to insertion sort when a partition fits within the 64-byte leaf budget. The experiment isolates the cost of continuing Quicksort down to one element: the pure_quick baseline uses the same partitioning helper without the larger cutoff.
The cutoff reduces partitioning work on small ranges, but it does not remove Quicksort's data-dependent branches or its worst-case behavior.
mean_pivot_quick performs Hoare partitioning and then scans both partitions again to collect sums and minimum/maximum keys. Those statistics choose subsequent mean pivots and let the algorithm skip all-equal ranges.
The current implementation does not collect those statistics during the partition pass. The extra scans are part of the trade-off. Mean pivots are clamped to ensure progress when integer division, especially with negative keys, would otherwise choose the maximum key.
boundary_trimmed_merge changes the starting point from top-down partitioning to bottom-up merging:
- Sort 64-byte leaves with insertion sort.
- Complete the early merge passes within each 8 KiB tile.
- Skip a merge if the two runs are already ordered at their boundary.
- Otherwise, search outward from the boundary to find the overlapping middle range. Short linear scans are followed by boundary checks, exponential search, and binary search.
- For a small or strongly asymmetric overlap, copy only the smaller side to scratch space and merge back directly. For a larger balanced overlap, use a bidirectional merge into scratch space, then copy the result back.
This is the most useful direction in the recorded append-tail and jittered workloads. It also has substantial regressions on some other inputs, shown below.
tiled_pingpong_merge also uses 8 KiB tiles, but alternates source and destination buffers between merge passes. It uses binary searches to trim the overlap and copies the already ordered outer ranges to the destination when needed.
It also probes global ordering trends, adjusts mostly descending input, and confirms sortedness before taking an early return. The probe alone is not treated as proof that the array is sorted.
Both merge variants use conditional selection in their merge kernels. AI helped implement these kernels, boundary searches, and tiling. Whether the compiler emits cmov, conditional-select instructions, or branches depends on the target and compiler; the algorithms are not entirely branch-free.
The initial implementation and the archived Linux hardware-counter study below concluded with Ideas 1–4. The ideas in this section were added later as follow-up experiments sparked by questions that came up after finishing Idea 4.
After finishing Idea 4, a natural follow-up question came up: since each 64-byte leaf holds a fixed number of elements (16× 4B keys or 8× 8B records), what happens if we vectorize the 64-byte leaf sort and the overlapping merge step using SIMD bitonic sorting networks?
simd_tiled_pingpong_merge_sort reuses Idea 4's 8 KiB tiles, binary boundary trimming, and ping-pong buffer swaps, while replacing full 64-byte leaves and complete vector overlaps with a bitonic network (src/simd/network.hpp). For 8-byte records, comparisons use the signed 32-bit key and move the 32-bit entity ID alongside it. Equal keys can change order.
Set HSORT_SIMD_ISA before launch to auto (default), scalar, sse2, avx2, avx512f, or neon. Auto currently chooses AVX2 or SSE2 on x64, NEON on supported ARM64 builds, and scalar elsewhere. Select avx512f to use the shared 512-bit kernel on AVX-512F and compatible AVX10.2 CPUs. HSORT_SIMD_STAGE accepts leaf, merge, and both (default) so the leaf and merge vectorization stages can be isolated independently. The profiler label records the selected kernel, active stages, and detected CPU capability. See the Windows x64 AVX2 follow-up benchmark for full comparisons across all eight sorts and stage-by-stage isolation of SIMD leaf vs. SIMD merge.
simd_transpose_tiled_merge_sort (simd_transpose_merge) addresses the bottlenecks observed in Idea 5 (cross-lane permute latency, 21-cycle serial loop-carried carry dependency floor, LLVM AArch64 b.ge/b.le De-If-Conversion traps, 128-bit NEON 8B 2-lane AoS overhead, dirtying clean cache lines on pre-sorted blocks, and 8 MB scratch page-fault overhead on mostly-descending inputs) by lifting the core principles of Ideas 1, 3, and 4 directly into x86-64 AVX2 (256-bit) and ARM64 NEON (128-bit) register architectures:
-
Vertical Sorting Network + In-Register Matrix Transpose for 256B Quad-Leaves (
4 * LEAF_SIZE): Loads 4 cache lines (8 YMM registers on AVX2 / 16 Q registers on ARM64 NEON: 64× 4B keys or 32× 8B records), sorts columns vertically with zero shuffles, transposes the register matrix ($8 \times 8$ or$4 \times 4 \times 4$ ), and finishes merging the 256B quad-leaf in registers—eliminating the first two intra-tile merge passes (width = LEAF_SIZE, 2 * LEAF_SIZE) while keeping the remaining 5 intra-tile passes odd. -
ISA-Specific Fast Bitonic Butterflies & ARM64
vld2q_s32/vst2q_s32Hardware De-Interleaved 4-Record SoA:-
x86-64 AVX2: Replaces 3-cycle cross-lane variable permutes (
vpermd) with 1-cycle in-lane_mm256_shuffle_epi32and immediate blends, and compares 8B records ({ key, entity_id }) with a single_mm256_cmpgt_epi32per stage while preserving equal-key records. -
ARM64 NEON: Replaces
vtrn1q_s64(which Clang compiled into extramov+insinstructions) with a symmetric 3-stagevzip1q_s32/vzip2q_s32butterfly, and uses hardwarevld2q_s32/vst2q_s32key/ID de-interleaving (AoS → SoA) so both 256B Quad-Leaves and Dual-Chain merges process 4 records per vector (amortizing the 6-cycle L1D load-to-address pointer dependency from 6.0 to 1.5 cycles/record).
-
x86-64 AVX2: Replaces 3-cycle cross-lane variable permutes (
-
Dual-Chain (
carry_fwd+carry_bwd) Branchless SIMD Merge &__builtin_unpredictable: Extends Idea 3's bidirectional merge to SIMD bitonic merging by advancing two independent SIMD merge chains from the front and back simultaneously while moving vector reversal off the loop-carriedcarrypath, and enforces hardwarecsel/csetviaHSORT_UNPREDICTABLE(__builtin_unpredictable) to block LLVM AArch64 De-If-Conversion. -
Adaptive Distribution Fast-Paths: Skips memory stores on already-sorted 256B quad-leaves to keep cache lines Clean; detects disjoint reversed runs (
src[end - 1] <= src[begin]) inO(1)(2.4×faster on6_Organ_Pipe); runs a zero-allocation in-place bounded insertion sort (try_bounded_inplace_insertion_sort) after reversing descending inputs to eliminate 2,048 OS soft page faults on4_Mostly_Descending; and streams equal-key plateaus (kl == kr && l_fwd[LANES - 1] == kl) at L1 copy bandwidth. -
Stack-Resident L1 Scratch for
N <= TILE_SIZE(8 KiB) & Single-TU Inlining: Avoids heap allocation on small/medium arrays and eliminates non-volatile SIMD register spill overhead across leaf and merge calls.
Idea 6 Head-to-Head Results ① — Windows ARM64 (N = 1,000,000, Snapdragon X Elite ARM64_Oryon · clang++ 23.1.5 -O3)
4-Byte Integer Keys (4B_Int32, median time in ms / hardware thread cycles in M)
| Workload | std::sort |
std::stable_sort |
Idea 4 (Scalar) | Idea 5 (NEON) | Idea 6 (Before) | Idea 6 (After) | vs. std::sort |
vs. Before |
|---|---|---|---|---|---|---|---|---|
| Random 3D distances | 18.86 (55.5M) | 13.55 (39.9M) | 62.50 (184.5M) | 28.82 (84.7M) | 66.54 (185.4M) | 9.40 (27.7M) | 2.01× | 7.08× |
| Frame jitter | 16.30 (48.0M) | 11.94 (35.3M) | 30.91 (91.1M) | 15.96 (47.3M) | 31.22 (91.4M) | 6.21 (18.5M) | 2.62× | 5.03× |
| Append 5% tail | 16.46 (48.4M) | 8.18 (24.2M) | 5.90 (17.4M) | 5.74 (16.8M) | 6.49 (17.5M) | 3.24 (9.6M) | 5.07× | 2.00× |
| Distance buckets | 6.89 (20.2M) | 14.35 (42.3M) | 37.35 (110.0M) | 28.80 (84.8M) | 37.57 (110.7M) | 8.50 (24.7M) | 0.81× (1.69× vs stable) | 4.42× |
| Mostly descending | 4.72 (13.9M) | 11.55 (34.0M) | 3.33 (9.5M) | 3.55 (10.4M) | 2.78 (8.1M) | 0.78 (2.3M) | 6.03× | 3.55× |
| Gaussian-like | 14.99 (44.2M) | 16.95 (50.1M) | 57.92 (170.8M) | 28.60 (84.5M) | 58.12 (170.7M) | 9.74 (28.8M) | 1.54× | 5.96× |
| Organ pipe | 36.58 (108.0M) | 10.88 (32.0M) | 7.53 (22.2M) | 9.67 (28.5M) | 7.57 (22.2M) | 2.86 (8.4M) | 12.77× | 2.64× |
8-Byte Key + Entity ID Records (8B_Record, median time in ms / hardware thread cycles in M)
| Workload | std::sort |
std::stable_sort |
Idea 4 (Scalar) | Idea 5 (NEON) | Idea 6 (Before) | Idea 6 (After) | vs. std::sort |
vs. Before |
|---|---|---|---|---|---|---|---|---|
| Random 3D distances | 51.36 (150.8M) | 44.03 (129.7M) | 68.43 (201.9M) | 51.21 (151.0M) | 69.52 (204.6M) | 18.18 (54.0M) | 2.83× | 3.82× |
| Frame jitter | 28.81 (85.3M) | 34.92 (103.1M) | 37.44 (110.3M) | 28.85 (85.5M) | 37.99 (111.7M) | 13.51 (39.7M) | 2.13× | 2.81× |
| Append 5% tail | 18.10 (53.4M) | 19.88 (58.5M) | 9.08 (26.5M) | 10.89 (32.0M) | 9.66 (28.4M) | 6.30 (18.7M) | 2.87× | 1.53× |
| Distance buckets | 20.80 (61.5M) | 43.99 (129.7M) | 42.74 (126.4M) | 50.77 (150.0M) | 44.51 (131.0M) | 15.47 (45.6M) | 1.35× | 2.88× |
| Mostly descending | 3.86 (11.5M) | 30.60 (90.8M) | 5.79 (17.1M) | 5.98 (17.7M) | 6.17 (18.2M) | 0.86 (2.6M) | 4.48× | 7.15× |
| Gaussian-like | 44.63 (131.7M) | 43.88 (129.5M) | 63.59 (187.9M) | 50.85 (150.0M) | 64.22 (189.2M) | 18.95 (55.7M) | 2.36× | 3.39× |
| Organ pipe | 38.99 (115.3M) | 25.91 (76.6M) | 11.07 (32.7M) | 18.40 (54.4M) | 11.55 (34.0M) | 6.10 (18.0M) | 6.39× | 1.89× |
4-Byte Integer Keys (key_only_4b, median time in ms)
| Workload | std::sort |
Idea 3 | Idea 4 | Idea 5 | Idea 6 | vs. std::sort |
vs. Idea 4 | vs. Idea 5 |
|---|---|---|---|---|---|---|---|---|
| Random 3D distances | 45.54 | 24.51 | 22.56 | 13.14 | 6.76 | 6.73× | 3.33× | 1.94× |
| Frame jitter | 26.24 | 15.62 | 16.64 | 10.32 | 5.90 | 4.45× | 2.82× | 1.75× |
| Append 5% tail | 17.50 | 3.76 | 4.57 | 3.63 | 3.06 | 5.71× | 1.49× | 1.19× |
| Distance buckets | 22.88 | 24.42 | 22.27 | 13.10 | 6.55 | 3.49× | 3.40× | 2.00× |
| Mostly descending | 3.30 | 19.30 | 2.98 | 2.82 | 2.23 | 1.48× | 1.34× | 1.27× |
| Gaussian-like | 40.68 | 24.29 | 22.79 | 13.33 | 6.98 | 5.83× | 3.27× | 1.91× |
| Organ pipe | 39.97 | 11.37 | 9.24 | 4.48 | 3.86 | 10.34× | 2.39× | 1.16× |
8-Byte Key + Entity ID Records (key_id_8b, median time in ms)
| Workload | std::sort |
Idea 3 | Idea 4 | Idea 5 | Idea 6 | vs. std::sort |
vs. Idea 4 | vs. Idea 5 |
|---|---|---|---|---|---|---|---|---|
| Random 3D distances | 43.85 | 32.25 | 29.32 | 32.54 | 18.19 | 2.41× | 1.61× | 1.79× |
| Frame jitter | 25.90 | 19.05 | 21.99 | 21.62 | 14.00 | 1.85× | 1.57× | 1.54× |
| Append 5% tail | 17.46 | 4.74 | 8.33 | 9.18 | 6.56 | 2.66× | 1.27× | 1.40× |
| Distance buckets | 22.70 | 32.63 | 29.56 | 33.21 | 18.30 | 1.24× | 1.62× | 1.81× |
| Mostly descending | 4.33 | 22.67 | 6.01 | 6.82 | 4.47 | 0.97× | 1.34× | 1.53× |
| Gaussian-like | 39.14 | 32.21 | 29.85 | 33.04 | 18.75 | 2.09× | 1.59× | 1.76× |
| Organ pipe | 40.33 | 12.45 | 13.07 | 13.67 | 10.75 | 3.75× | 1.22× | 1.27× |
See the Idea 6 Design and Benchmark Guide for full architectural diagrams, ARM64 NEON assembly analysis, iterative trial-and-error log (v1–v4), and multi-scale benchmark tables.
All inputs are generated by generate_game_workload. They are synthetic workloads, not measurements from a running game engine.
| ID | Workload | What is generated |
|---|---|---|
| 0 | Random 3D distances | Squared-distance keys from pseudo-random 3D coordinates. The resulting keys are not uniformly distributed, despite the profiler's legacy 0_Uniform_Random label. |
| 1 | Frame jitter | Sort points by distance, perturb their coordinates, then recompute distance keys. |
| 2 | Append 5% tail | A sorted prefix followed by floor(N / 20) unsorted new keys. |
| 3 | Distance buckets | Divide distance keys by 1,000,000 to create roughly 300 buckets and many duplicates. |
| 4 | Mostly descending | Descending keys perturbed by approximately 1% random adjacent swaps. |
| 5 | Gaussian-like | Sum four pseudo-random integer samples to obtain a bell-shaped distribution, not an exact normal distribution. |
| 6 | Organ pipe | Arrange sorted keys into an ascending then descending mountain shape. |
All three platforms have measurements at 1,000,000 elements. Each cell shows Idea 5 → Idea 6 in median milliseconds per array. The speedup in parentheses is the Idea 5 time divided by the Idea 6 time on the same machine, calculated before rounding.
4-byte integer keys
| Workload | Linux x86-64 · AVX2 | Windows x64 · AVX2 | Windows ARM64 · NEON |
|---|---|---|---|
| Random 3D distances | 17.68 → 10.46 (1.69×) | 13.14 → 6.76 (1.94×) | 28.82 → 9.40 (3.07×) |
| Frame jitter | 13.09 → 7.91 (1.65×) | 10.32 → 5.90 (1.75×) | 15.96 → 6.21 (2.57×) |
| Append 5% tail | 4.57 → 2.94 (1.55×) | 3.63 → 3.06 (1.19×) | 5.74 → 3.24 (1.77×) |
| Distance buckets | 17.66 → 9.04 (1.95×) | 13.10 → 6.55 (2.00×) | 28.80 → 8.50 (3.39×) |
| Mostly descending | 3.32 → 0.76 (4.40×) | 2.82 → 2.23 (1.27×) | 3.55 → 0.78 (4.54×) |
| Gaussian-like | 17.61 → 10.76 (1.64×) | 13.33 → 6.98 (1.91×) | 28.60 → 9.74 (2.94×) |
| Organ pipe | 6.02 → 2.97 (2.03×) | 4.48 → 3.86 (1.16×) | 9.67 → 2.86 (3.37×) |
8-byte key + entity ID records
| Workload | Linux x86-64 · AVX2 | Windows x64 · AVX2 | Windows ARM64 · NEON |
|---|---|---|---|
| Random 3D distances | 42.55 → 28.32 (1.50×) | 32.54 → 18.19 (1.79×) | 51.21 → 18.18 (2.82×) |
| Frame jitter | 31.65 → 22.90 (1.38×) | 21.62 → 14.00 (1.54×) | 28.85 → 13.51 (2.14×) |
| Append 5% tail | 13.54 → 9.45 (1.43×) | 9.18 → 6.56 (1.40×) | 10.89 → 6.30 (1.73×) |
| Distance buckets | 43.22 → 24.09 (1.79×) | 33.21 → 18.30 (1.81×) | 50.77 → 15.47 (3.28×) |
| Mostly descending | 10.31 → 1.30 (7.95×) | 6.82 → 4.47 (1.53×) | 5.98 → 0.86 (6.93×) |
| Gaussian-like | 43.46 → 29.63 (1.47×) | 33.04 → 18.75 (1.76×) | 50.85 → 18.95 (2.68×) |
| Organ pipe | 18.20 → 10.50 (1.73×) | 13.67 → 10.75 (1.27×) | 18.40 → 6.10 (3.02×) |
- The Linux x86-64 AVX2 run used an Intel Core i5-1135G7 and GCC 15.2.0 with
-O3. 4B CSV · 8B CSV - The Windows x64 AVX2 run used an Intel Core Ultra 7 270K Plus and
g++ -O3. The separate MSVC run compared Idea 5 with seven earlier sorts before Idea 6 was added. 4B CSV · 8B CSV · MSVC report - The Windows ARM64 NEON run used a Snapdragon X Elite and Clang 23.1.5 with
-O3. The Idea 6 times are for the optimized NEON implementation (v3). 4B and 8B CSV
Linux ARM64 NEON passed correctness checks under QEMU. Native Linux ARM64 timings for Ideas 5 and 6 are missing from docs/. Linux benchmark notes
The ten original Linux counter CSVs cover the standard-library baselines and Ideas 1–4. Linux cycle, cache, and branch counts for Ideas 5 and 6 are unavailable. The following tables use the stored counters for 4-byte integer keys at N = 1,000,000. Linux counter CSV
The counter files omit the original CPU model, compiler version, OS details, exact build revision, and per-trial samples, which limits reproducibility.
M means one million cycles. Parentheses show std::sort cycles / algorithm cycles: a ratio above 1 means fewer recorded cycles than std::sort, not an equivalent wall-clock speedup.
| Workload | std::sort |
std::stable_sort |
Boundary-trimmed merge | Tiled ping-pong merge |
|---|---|---|---|---|
| Random 3D distances | 230.79M | 278.63M | 142.74M (1.62×) | 139.40M (1.66×) |
| Frame jitter | 137.26M | 150.98M | 90.97M (1.51×) | 97.25M (1.41×) |
| Append 5% tail | 85.48M | 38.75M | 24.66M (3.47×) | 28.76M (2.97×) |
| Distance buckets | 114.67M | 164.06M | 142.81M (0.80×) | 139.54M (0.82×) |
| Mostly descending | 23.68M | 40.15M | 110.38M (0.21×) | 17.14M (1.38×) |
| Gaussian-like | 207.85M | 259.24M | 142.79M (1.46×) | 139.30M (1.49×) |
| Organ pipe | 246.65M | 34.95M | 61.74M (3.99×) | 61.05M (4.04×) |
The counterexamples matter: both custom merge variants use more cycles than std::sort on duplicate-heavy distance buckets, and boundary-trimmed merge uses about 4.66× as many cycles on mostly descending input. std::stable_sort beats both on organ-pipe input. There is no single winner across these workloads.
For the random 3D-distance workload above:
| Algorithm | IPC | L1D read hit rate | L1D read misses | Branch prediction hit rate |
|---|---|---|---|---|
std::sort |
0.63 | 97.83% | 662,145 | 75.54% |
boundary_trimmed_merge |
2.19 | 95.11% | 2,020,305 | 95.02% |
tiled_pingpong_merge |
2.21 | 96.93% | 1,256,029 | 94.89% |
The merge variants have fewer recorded cycles, higher IPC, and better branch prediction hit rates here, but more L1D read misses and lower L1D read hit rates. These observations do not establish improved cache behavior as the cause of the cycle reduction. Hit rates also have different access-count denominators, so compare absolute counts as well as percentages.
The ten Linux counter CSVs cover both formats at N = 16, 64, 256, 1024, 2048, 8192, 32768, 262144, 1000000, 5000000. At one million elements, the 8-byte tiled ping-pong merge uses about 16.3% more cycles than std::sort on the mostly descending workload.
make -f makefile.txt bench runs nine algorithms, seven scenarios, and five sizes (128, 2048, 8192, 131072, 1000000). It reports the median of five per-array timing samples, batching smaller arrays to reduce timer overhead. Input generation, the input copy, and result verification are outside the timed interval; work performed inside the sort, including scratch allocation and internal copies, remains included.
This runner verifies sorted keys after each timed sample and checks record IDs/payloads in 8-byte mode. Its trimmed_merge output label refers to boundary_trimmed_merge_sort.
Use Linux with GCC, Bash, and hardware performance-counter access already permitted by the host. The pure profiler calls perf_event_open directly. The separate run_perf_csv.sh wrapper uses perf stat around the whole process, so its measurement scope differs.
# One size, three repetitions, both 4B and 8B formats.
bash utility/linux/run_pure_perf.sh 1000000 3 results.csv
# All ten sizes, three repetitions, five seconds between sizes.
# Use a separate output directory to preserve the committed measurements.
bash utility/linux/run_pure_perf.sh --all 3 5 results/linuxThe scripts compile the profiling binaries and write CSV/Markdown summaries; the full sweep also writes pure_cache_results_all.csv.
The pure profiler reuses seed 42, copies the source before each measured sort, collects counters in two separate passes, and averages counter values across repetitions. It excludes input generation and the pre-sort copy, but includes sort-internal allocation/copies and some counter-control overhead. The copy affects cache state; this is not a controlled cold-cache experiment. It does not perform the wall-clock runner's result verification, so run the correctness suite first.
Counter support and permissions vary by CPU, kernel, VM, and container. A failed cycle/instruction counter open stops the profiler; unavailable optional counters can appear as zero counts and misleading 100% hit rates. Check counter availability before interpreting results. Events are enabled individually and may be multiplexed/scaled, so short runs and cross-event ratios need particular care. The generic cache events labelled LLC have CPU-dependent meanings. CPU affinity is not pinned by the Linux pure profiler.
If access is denied, use an environment with appropriate PMU access or consult its administrator. Do not assume that changing system-wide security settings is required or appropriate. See the Linux profiling guide for script details.
The Windows profiler uses QueryPerformanceCounter for elapsed time and QueryThreadCycleTime for thread cycles. These are not Linux L1D/LLC/branch counters and should not be compared as if the metric sets were identical. Its warmup, small-input batching, and median aggregation also differ from the Linux pure profiler.
# One size, three repetitions, both formats.
.\utility\windowsARM\run_pure_perf.bat 1000000 3 results.csv
# Full sweep into a separate output directory.
.\utility\windowsARM\run_pure_perf.bat --all 3 5 results\windowsARMThe script prefers Visual Studio's compiler and selects ARM64 on an ARM64 host, with Clang/GCC fallbacks. Install the relevant C++ toolchain and SDK, and verify the reported architecture rather than assuming every fallback produces a native ARM64 binary. See the Windows ARM64 guide.
For new benchmark reports, include the commit SHA, CPU/cache configuration, OS, compiler and standard-library versions, flags, affinity/power settings, counter availability, item format, N, workload, seed, and repeated measurements. Keep wall-clock timings and hardware-counter runs clearly separated.
- API: The functions accept
hsort::Item*and an element count. They sort ascending by the signed 32-bit key. The build chooses eitherint32_torDistanceRecord { key, entity_id }with-DBENCH_RECORD=1; there is no generic iterator/comparator interface. - Memory: For non-leaf inputs, boundary-trimmed merge allocates scratch space for
Nitems. Tiled ping-pong merge does the same when its global-trend fast path does not finish the sort. Half-buffer merging reduces copying for selected overlaps, not the allocated capacity. Allocation can fail. - Complexity: The merge variants have O(N log N) worst-case work and O(N) auxiliary storage. The custom Quicksort variants have no introspective fallback and can take O(N²) work on unfavorable inputs.
- Stability: Boundary-trimmed merge preserves equal-key order, with dedicated 8-byte record regressions against
std::stable_sort. The custom Quicksort variants are unstable. Tiled ping-pong merge is also not guaranteed stable because its global descending-input adjustment can reorder equal-key records. - Portability: The 64-byte and 8 KiB constants are fixed, not detected from the machine. Generated instructions and performance depend on the CPU, compiler, flags, standard-library implementation, and workload.
- Evidence: Synthetic workloads and a passing test suite do not establish production readiness. The benchmarks do not cover arbitrary user-defined comparators, larger records, parallel sorting, or every adversarial input.
My takeaway is that boundary trimming is worth exploring when much of the input is already ordered, while ping-pong merging offers a different copying trade-off. The useful next step is to measure the actual workload and explain both the wins and the losses, rather than assuming that a cache-sized block makes a sort universally faster.
| Path | Purpose |
|---|---|
include/hybrid_sorts.hpp |
Item types, constants, aligned buffer, shared kernels, and public declarations |
src/baseline_sorts.cpp |
Basic Quicksort and standard-library baselines |
src/ |
Initial four custom implementations (Ideas 1–4), follow-up SIMD implementations (Idea 5+), workload generator, correctness tests, and timing runner |
makefile.txt |
GCC test and benchmark targets |
generate_solution.bat |
Visual Studio x64 solution generator |
utility/linux/ |
Linux PMU profiler and external perf stat wrapper |
utility/windowsARM/ |
Windows timing/thread-cycle profiler and build scripts |
docs/linux/ |
Linux counter CSVs, plots, and x86-64 AVX2 sort timings |
docs/windowsARM/ |
Windows ARM64 (Snapdragon X Elite / Oryon) N = 1,000,000 CSV and Markdown report |
Please roast my code, but tell me why! I am still learning, and feedback on correctness, algorithm design, benchmarking, and low-level implementation is welcome.
Open an issue or submit a pull request. For a bug, include a small failing input and the item format. For a performance claim, include the environment, exact command, and raw results so the comparison can be checked. References to related sorting techniques are welcome too.
This project is licensed under the MIT License.