パターン撃退型クイックソートを使用する

パターン撃退型クイックソート (pattern-defeating quicksort) は、イントロソートを拡張したハイブリッドな比較ソートである。

Rust の標準ライブラリや Go 1.19 以降の sort パッケージなどでも採用されている。

基本はロムート分割型クイックソートだが、次の仕掛けで「悪い入力パターン」を撃退する。

  1. ピボット選択: 小区間は 3 要素の中央値、大きめの区間は Tukey の ninther(9 要素の疑似中央値)を使う。
  2. 等値の扱い: 直前の分割でピボットと等しい値が左端に接しているときは、等値を左へ寄せる分割に切り替え、等値だらけの区間を再帰から外す。
  3. 不均衡の検知: 左右の部分配列が元サイズの 1/8 未満に偏ったら、候補位置を入れ替えてパターンを崩す。偏りが \(\lfloor \log_2 n \rfloor\) 回続くとヒープソートへフォールバックする。
  4. ほぼ整列の検知: 分割がほとんど動かなかった区間には、移動回数に上限付きの部分挿入ソートを試し、成功すればその場で打ち切る。
  5. 小区間: 要素数が閾値未満なら挿入ソートで仕上げる。
procedure pdqsort(A, lo, hi, bad_allowed, leftmost)
  while lo <= hi
    size = hi - lo + 1
    if size < INSERTION_THRESHOLD then
      insertion_sort(A, lo, hi)
      return
    choose_pivot_median3_or_ninther(A, lo, hi)
    if not leftmost and A[lo - 1] = A[lo] then
      lo = partition_left(A, lo, hi) + 1
      continue
    pivot_pos, already = partition_right(A, lo, hi)
    l = pivot_pos - lo
    r = hi - pivot_pos
    if l < size / 8 or r < size / 8 then
      if bad_allowed = 0 then
        heapsort(A, lo, hi)
        return
      bad_allowed = bad_allowed - 1
      shuffle_candidates(A, lo, pivot_pos, hi)
    else if already and partial_insertion(A, lo, pivot_pos - 1)
                    and partial_insertion(A, pivot_pos + 1, hi) then
      return
    pdqsort(A, lo, pivot_pos - 1, bad_allowed, leftmost)
    lo = pivot_pos + 1
    leftmost = false

procedure sort(A)
  if length(A) > 1 then
    pdqsort(A, 0, length(A) - 1, floor(log2(length(A))), true)

平均計算量は \(O(n \log n)\)、最悪もヒープソートへの切り替えにより \(O(n \log n)\) に抑えられる。不安定である。

類似アルゴリズムとの相違点

イントロソートは再帰深度の上限でヒープソートへ切り替えるのに対し、 パターン撃退型クイックソートは「分割の偏り」を数え、加えて等値の片寄せや部分挿入による早期終了、 不均衡時の候補シャッフルで悪パターン自体を崩す。

デュアルピボットクイックソートは 1 回の走査で 3 分割する単一アルゴリズムの改良だが、 パターン撃退版は単一ピボットのままハイブリッド戦略で最悪ケースと現実的な入力パターンの両方に備える。

時間計算量および空間計算量を計測する

Size Average time (s) Maximum time (s) Average memory (KiB) Maximum memory (KiB)
256 0.000009 0.000129 0 0
512 0.000019 0.000148 0 0
1024 0.000040 0.000242 0 0
2048 0.000086 0.000442 0 0
4096 0.000189 0.000841 0 0
8192 0.000398 0.000662 0 0
16384 0.000776 0.001230 0 0
32768 0.001746 0.003446 0 0
65536 0.003707 0.007507 0 0
131072 0.006709 0.071133 0 0
262144 0.011601 0.019176 0 0
計測に使用したコードを表示する

#!/usr/bin/env swift
import Foundation

// This standalone Swift driver creates the same temporary Docker build
// context as the former shell wrapper.  The benchmark program itself remains
// embedded below so readers can copy one complete, reproducible file.
struct BenchmarkError: Error, CustomStringConvertible {
    let message: String

    var description: String { message }

    init(_ message: String) {
        self.message = message
    }
}

func runCommand(_ executable: String, _ arguments: [String]) throws {
    let process = Process()
    process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
    process.arguments = [executable] + arguments
    process.standardInput = FileHandle.standardInput
    process.standardOutput = FileHandle.standardOutput
    process.standardError = FileHandle.standardError

    do {
        try process.run()
    } catch {
        throw BenchmarkError("Could not start \(executable): \(error)")
    }
    process.waitUntilExit()
    guard process.terminationStatus == 0 else {
        throw BenchmarkError(
            "Command failed (\(process.terminationStatus)): " +
            "\(executable) \(arguments.joined(separator: " "))"
        )
    }
}

do {
    // The UUID avoids collisions when two benchmark copies are run at once.
    let workdir = FileManager.default.temporaryDirectory
        .appendingPathComponent("swift-sort-benchmark-\(UUID().uuidString)")
    try FileManager.default.createDirectory(at: workdir, withIntermediateDirectories: true)
    defer { try? FileManager.default.removeItem(at: workdir) }

    // A raw Swift string is used so the nested main.swift keeps its own
    // interpolation expressions such as \(seed) until Docker compiles it.
    let dockerfile = #"""
FROM swift:6.0

WORKDIR /app

RUN cat > alloc_track.c <<'ALLOC'
#define _GNU_SOURCE
#include <dlfcn.h>
#include <malloc.h>
#include <stdatomic.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static atomic_size_t live_bytes = 0;
static atomic_size_t peak_bytes = 0;

static void *(*real_malloc)(size_t) = NULL;
static void *(*real_calloc)(size_t, size_t) = NULL;
static void *(*real_realloc)(void *, size_t) = NULL;
static void (*real_free)(void *) = NULL;

static void init_reals(void) {
    if (real_malloc) {
        return;
    }
    real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
    real_calloc = (void *(*)(size_t, size_t))dlsym(RTLD_NEXT, "calloc");
    real_realloc = (void *(*)(void *, size_t))dlsym(RTLD_NEXT, "realloc");
    real_free = (void (*)(void *))dlsym(RTLD_NEXT, "free");
}

static void record_alloc(size_t size) {
    size_t live = atomic_fetch_add(&live_bytes, size) + size;
    size_t peak = atomic_load(&peak_bytes);
    while (live > peak) {
        if (atomic_compare_exchange_weak(&peak_bytes, &peak, live)) {
            break;
        }
    }
}

void alloc_track_reset_peak(void) {
    atomic_store(&peak_bytes, atomic_load(&live_bytes));
}

size_t alloc_track_live(void) { return atomic_load(&live_bytes); }
size_t alloc_track_peak(void) { return atomic_load(&peak_bytes); }

void *malloc(size_t size) {
    init_reals();
    void *p = real_malloc(size);
    if (p) {
        record_alloc(malloc_usable_size(p));
    }
    return p;
}

void *calloc(size_t nmemb, size_t size) {
    init_reals();
    void *p = real_calloc(nmemb, size);
    if (p) {
        record_alloc(malloc_usable_size(p));
    }
    return p;
}

void *realloc(void *ptr, size_t size) {
    init_reals();
    size_t old_size = 0;
    if (ptr) {
        old_size = malloc_usable_size(ptr);
    }
    void *p = real_realloc(ptr, size);
    if (p) {
        atomic_fetch_sub(&live_bytes, old_size);
        record_alloc(malloc_usable_size(p));
    } else if (size == 0) {
        atomic_fetch_sub(&live_bytes, old_size);
    }
    return p;
}

void free(void *ptr) {
    init_reals();
    if (ptr) {
        atomic_fetch_sub(&live_bytes, malloc_usable_size(ptr));
        real_free(ptr);
    }
}

ALLOC

RUN cat > main.swift <<'SWIFT'
import Foundation
#if canImport(Glibc)
import Glibc
#elseif canImport(Darwin)
import Darwin
#endif

@_silgen_name("alloc_track_live") func alloc_track_live() -> Int
@_silgen_name("alloc_track_peak") func alloc_track_peak() -> Int
@_silgen_name("alloc_track_reset_peak") func alloc_track_reset_peak()

extension UnsafeMutableBufferPointer where Element == Int {
    func swapAt(_ i: Int, _ j: Int) {
        let t = self[i]; self[i] = self[j]; self[j] = t
    }
}

let MIN_POWER: Int = 8
let MAX_POWER: Int = 18
let RUNS: Int = 8192
func insertion_sort(_ a: inout [Int]) {
    a.withUnsafeMutableBufferPointer { insertion_sort($0) }
}

func insertion_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    if a.count < 2 {
        return
    }
    for i in 1..<a.count {
        var j = i
        while j > 0 && a[j - 1] > a[j] {
            a.swapAt(j - 1, j)
            j -= 1
        }
    }
}

func sift_down(_ a: UnsafeMutableBufferPointer<Int>, _ root: Int, _ end: Int) {
    var root = root
    while true {
        let child = root * 2 + 1
        if child > end {
            break
        }
        var swap_idx = child
        if child < end && a[child] < a[child + 1] {
            swap_idx = child + 1
        }
        if a[root] >= a[swap_idx] {
            break
        }
        a.swapAt(root, swap_idx)
        root = swap_idx
    }
}

func heap_sort(_ a: inout [Int]) {
    a.withUnsafeMutableBufferPointer { heap_sort($0) }
}

func heap_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    if a.count <= 1 {
        return
    }
    for start in (0..<(a.count / 2)).reversed() {
        sift_down(a, start, a.count - 1)
    }
    for end in (1..<a.count).reversed() {
        a.swapAt(0, end)
        sift_down(a, 0, end - 1)
    }
}



fileprivate let INSERTION_SORT_THRESHOLD = 24
fileprivate let NINTHER_THRESHOLD = 128
fileprivate let PARTIAL_INSERTION_SORT_LIMIT = 8

fileprivate func floor_log2(_ n: Int) -> Int {
    Int.bitWidth - n.leadingZeroBitCount - 1
}

fileprivate func sort2(_ a: UnsafeMutableBufferPointer<Int>, _ i: Int, _ j: Int) {
    if a[j] < a[i] {
        a.swapAt(i, j)
    }
}

fileprivate func sort3(_ a: UnsafeMutableBufferPointer<Int>, _ i: Int, _ j: Int, _ k: Int) {
    sort2(a, i, j)
    sort2(a, j, k)
    sort2(a, i, j)
}

fileprivate func partial_insertion_sort_range(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int) -> Bool {
    if hi <= lo {
        return true
    }
    var limit = 0
    for i in (lo + 1)...hi {
        if a[i] < a[i - 1] {
            let tmp = a[i]
            var j = i
            while true {
                a[j] = a[j - 1]
                j -= 1
                if j == lo || !(tmp < a[j - 1]) {
                    break
                }
            }
            a[j] = tmp
            limit += i - j
            if limit > PARTIAL_INSERTION_SORT_LIMIT {
                return false
            }
        }
    }
    return true
}

/// Partition `[lo, hi]` around pivot at `lo`. Equals go to the right.
/// Returns `(pivot_pos, already_partitioned)`.
fileprivate func partition_right_range(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int) -> (Int, Bool) {
    let pivot = a[lo]
    var first = lo
    var last = hi + 1

    while true {
        first += 1
        if !(a[first] < pivot) {
            break
        }
    }

    if first - 1 == lo {
        while true {
            if first >= last {
                break
            }
            last -= 1
            if a[last] < pivot {
                break
            }
        }
    } else {
        while true {
            last -= 1
            if a[last] < pivot {
                break
            }
        }
    }

    let already_partitioned = first >= last
    while first < last {
        a.swapAt(first, last)
        while true {
            first += 1
            if !(a[first] < pivot) {
                break
            }
        }
        while true {
            last -= 1
            if a[last] < pivot {
                break
            }
        }
    }

    let pivot_pos = first - 1
    a[lo] = a[pivot_pos]
    a[pivot_pos] = pivot
    return (pivot_pos, already_partitioned)
}

/// Partition `[lo, hi]` around pivot at `lo`. Equals go to the left.
fileprivate func partition_left_range(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int) -> Int {
    let pivot = a[lo]
    var first = lo
    var last = hi + 1

    while true {
        last -= 1
        if !(pivot < a[last]) {
            break
        }
    }

    if last + 1 == hi + 1 {
        while true {
            if first >= last {
                break
            }
            first += 1
            if pivot < a[first] {
                break
            }
        }
    } else {
        while true {
            first += 1
            if pivot < a[first] {
                break
            }
        }
    }

    while first < last {
        a.swapAt(first, last)
        while true {
            last -= 1
            if !(pivot < a[last]) {
                break
            }
        }
        while true {
            first += 1
            if pivot < a[first] {
                break
            }
        }
    }

    a[lo] = a[last]
    a[last] = pivot
    return last
}

fileprivate func pattern_defeating_quick_sort_loop(
    _ a: UnsafeMutableBufferPointer<Int>,
    _ lo: Int,
    _ hi: Int,
    _ bad_allowed: Int,
    _ leftmost: Bool
) {
    var lo = lo
    var bad_allowed = bad_allowed
    var leftmost = leftmost
    while lo <= hi {
        let size = hi - lo + 1
        if size < INSERTION_SORT_THRESHOLD {
            insertion_sort(UnsafeMutableBufferPointer(rebasing: a[lo..<(hi + 1)]))
            return
        }

        let s2 = size / 2
        if size > NINTHER_THRESHOLD {
            sort3(a, lo, lo + s2, hi)
            sort3(a, lo + 1, lo + (s2 - 1), hi - 1)
            sort3(a, lo + 2, lo + (s2 + 1), hi - 2)
            sort3(a, lo + (s2 - 1), lo + s2, lo + (s2 + 1))
            a.swapAt(lo, lo + s2)
        } else {
            sort3(a, lo + s2, lo, hi)
        }

        if !leftmost && !(a[lo - 1] < a[lo]) {
            lo = partition_left_range(a, lo, hi) + 1
            if lo > hi {
                return
            }
            continue
        }

        let (pivot_pos, already_partitioned) = partition_right_range(a, lo, hi)
        let l_size = pivot_pos - lo
        let r_size = hi - pivot_pos
        let highly_unbalanced = l_size < size / 8 || r_size < size / 8

        if highly_unbalanced {
            if bad_allowed == 0 {
                heap_sort(UnsafeMutableBufferPointer(rebasing: a[lo..<(hi + 1)]))
                return
            }
            bad_allowed -= 1

            if l_size >= INSERTION_SORT_THRESHOLD {
                a.swapAt(lo, lo + l_size / 4)
                a.swapAt(pivot_pos - 1, pivot_pos - l_size / 4)
                if l_size > NINTHER_THRESHOLD {
                    a.swapAt(lo + 1, lo + (l_size / 4 + 1))
                    a.swapAt(lo + 2, lo + (l_size / 4 + 2))
                    a.swapAt(pivot_pos - 2, pivot_pos - (l_size / 4 + 1))
                    a.swapAt(pivot_pos - 3, pivot_pos - (l_size / 4 + 2))
                }
            }

            if r_size >= INSERTION_SORT_THRESHOLD {
                a.swapAt(pivot_pos + 1, pivot_pos + (1 + r_size / 4))
                a.swapAt(hi, hi + 1 - r_size / 4)
                if r_size > NINTHER_THRESHOLD {
                    a.swapAt(pivot_pos + 2, pivot_pos + (2 + r_size / 4))
                    a.swapAt(pivot_pos + 3, pivot_pos + (3 + r_size / 4))
                    a.swapAt(hi - 1, hi - (r_size / 4))
                    a.swapAt(hi - 2, hi - (1 + r_size / 4))
                }
            }
        } else if already_partitioned
            && (pivot_pos == lo || partial_insertion_sort_range(a, lo, pivot_pos - 1))
            && (pivot_pos >= hi || partial_insertion_sort_range(a, pivot_pos + 1, hi))
        {
            return
        }

        if pivot_pos > lo {
            pattern_defeating_quick_sort_loop(a, lo, pivot_pos - 1, bad_allowed, leftmost)
        }
        lo = pivot_pos + 1
        leftmost = false
        if lo > hi {
            return
        }
    }
}

func pattern_defeating_quick_sort(_ a: inout [Int]) {
    a.withUnsafeMutableBufferPointer { pattern_defeating_quick_sort($0) }
}

func pattern_defeating_quick_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    if a.count <= 1 {
        return
    }
    let bad_allowed = floor_log2(a.count)
    pattern_defeating_quick_sort_loop(a, 0, a.count - 1, bad_allowed, true)
}


func benchmark_sort(_ array: inout [Int]) {

    pattern_defeating_quick_sort(&array)

}

func is_non_decreasing(_ a: [Int]) -> Bool {
    guard a.count >= 2 else { return true }
    for i in 1..<a.count {
        if a[i - 1] > a[i] { return false }
    }
    return true
}

func same_multiset(_ a: [Int], _ b: [Int]) -> Bool {
    if a.count != b.count {
        return false
    }

    var left = a
    var right = b
    left.sort()
    right.sort()
    return left == right
}

func check_correctness_case(_ label: String, _ input: [Int]) {
    var input = input
    let original = input

    benchmark_sort(&input)

    if !is_non_decreasing(input) {
        fatalError("correctness case \(label): output is not sorted")
    }

    if !same_multiset(input, original) {
        fatalError("correctness case \(label): elements were lost or added")
    }
}

// Skip cases larger than the algorithm's measured size cap (MAX_POWER). That
// cap exists because larger inputs are impractically slow; forcing them here
// would stall the published measurement script before any table rows print.
func check_correctness_case_within_limit(_ label: String, _ input: [Int]) {
    if input.count > (1 << MAX_POWER) {
        return
    }
    check_correctness_case(label, input)
}

func few_unique_values(_ size: Int, _ unique: Int, _ seed: UInt64) -> [Int] {
    var state = seed
    var result = [Int]()
    result.reserveCapacity(size)
    for _ in 0..<size {
        state ^= state << 13
        state ^= state >> 7
        state ^= state << 17
        result.append(Int(state % UInt64(unique)) + 1)
    }
    return result
}

func run_correctness_checks() {
    check_correctness_case("empty", [])
    check_correctness_case("single", [42])
    check_correctness_case("duplicates", [3, 1, 3, 2, 1, 2])
    check_correctness_case("sorted", [1, 2, 3, 4, 5])
    check_correctness_case("reverse", [5, 4, 3, 2, 1])
    check_correctness_case("all_equal", [7, 7, 7, 7])
    check_correctness_case("skewed_range", [1_000_000, 2, 1_000_001, 1, 999_999])
    // Static-buffer Grail skips the in-buffer build when key collection is sparse
    // (ideal_buffer = false). Exercising that path catches regressions in buffer gating.
    check_correctness_case(
        "few_keys_len16",
        [2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 1, 2, 3, 4, 1, 4]
    )
    // Seed 0 is a fixed point of the xorshift below, so it would degenerate into
    // yet another all-equal case instead of a 4-value mix. Start at 1.
    for seed in 1...32 {
        check_correctness_case(
            "few_keys_len32_seed_\(seed)",
            few_unique_values(32, 4, UInt64(seed))
        )
    }
    // Small-input cutoffs (insertion sort below 32 elements, etc.) hide duplicate-key
    // bugs in the recursive path, so repeat the duplicate cases at the smallest
    // benchmark size, which every algorithm must handle within reasonable time.
    check_correctness_case("all_equal_len256", [Int](repeating: 7, count: 256))
    for seed in 1...4 {
        check_correctness_case(
            "few_keys_len256_seed_\(seed)",
            few_unique_values(256, 4, UInt64(seed))
        )
    }
    // Blit's equal-key second sweep used to copy the whole range into a fixed
    // 512-element swap; lengths above that must still sort without panicking.
    // Respect MAX_POWER so algorithms with a low measured-size cap (slow,
    // sleep) do not hang here for minutes or months.
    check_correctness_case_within_limit("all_equal_len600", [Int](repeating: 7, count: 600))
    for seed in 1...4 {
        check_correctness_case_within_limit(
            "few_keys_len2048_seed_\(seed)",
            few_unique_values(2048, 4, UInt64(seed))
        )
    }
}


func shuffled(_ size: Int, seed: UInt64) -> [Int] {
    guard size > 0 else { return [] }

    var v = Array(1...size)
    var state = seed

    if size > 1 {
        for i in stride(from: size - 1, through: 1, by: -1) {
            state ^= state << 13
            state ^= state >> 7
            state ^= state << 17

            let j = Int(state % UInt64(i + 1))
            v.swapAt(i, j)
        }
    }

    return v
}

func micros(_ d: Duration) -> UInt64 {
    let c = d.components
    let fromSeconds = UInt64(c.seconds) * 1_000_000
    let fromAttos = UInt64(max(0, c.attoseconds / 1_000_000_000_000))
    return fromSeconds + fromAttos
}

func padLeft(_ value: String, _ width: Int) -> String {
    if value.count >= width {
        return value
    }
    return String(repeating: " ", count: width - value.count) + value
}

func formatSeconds(_ micros: UInt64) -> String {
    let whole = micros / 1_000_000
    let frac = micros % 1_000_000
    let fracStr = padLeft(String(frac), 6).replacingOccurrences(of: " ", with: "0")
    return "\(whole).\(fracStr)"
}

func input_array(_ size: Int, seed: UInt64) -> [Int] {
    shuffled(size, seed: seed)
}

/// Peak heap growth during `benchmark_sort`, in bytes (explicit buffers such as swap).
/// Kept in bytes so the parent can average before rounding; converting to KiB here
/// would truncate sub-KiB buffers to 0 in every run and hide them from the average.
func run_once(size: Int, seed: Int) -> (UInt64, Int) {
    var array = input_array(size, seed: UInt64(seed))

    let baseBytes = alloc_track_live()
    alloc_track_reset_peak()

    let start = ContinuousClock.now

    benchmark_sort(&array)

    let elapsed = ContinuousClock.now - start
    let peakBytes = alloc_track_peak()
    let auxBytes = max(0, peakBytes - baseBytes)

    let expected: [Int] = size > 0 ? Array(1...size) : []
    if array != expected {
        fatalError("sort failed with seed \(seed) for size \(size)")
    }

    return (micros(elapsed), auxBytes)
}

func run_child(_ args: [String]) {
    let size = Int(args[2])!
    let seed = Int(args[3])!
    let (elapsedUs, mem) = run_once(size: size, seed: seed)
    print("\(elapsedUs) \(mem)")
}

let args = CommandLine.arguments
if args.count > 1 && args[1] == "--run-once" {
    run_child(args)
} else {
    run_correctness_checks()

    let tableHeader =
        "| \(padLeft("Size", 10)) | " +
        "\(padLeft("Average time (s)", 16)) | " +
        "\(padLeft("Maximum time (s)", 16)) | " +
        "\(padLeft("Average memory (KiB)", 20)) | " +
        "\(padLeft("Maximum memory (KiB)", 20)) |"
    print(tableHeader)
    print("|-----------:|-----------------:|-----------------:|---------------------:|---------------------:|")

    for power in MIN_POWER...MAX_POWER {
        let size = 1 << power

        var totalTime: UInt64 = 0
        var maxTime: UInt64 = 0

        var totalMem = 0
        var maxMem = 0

        for seed in 1...RUNS {
            let process = Process()
            process.executableURL = URL(fileURLWithPath: args[0])
            process.arguments = ["--run-once", "\(size)", "\(seed)"]
            let stdout = Pipe()
            let stderr = Pipe()
            process.standardOutput = stdout
            process.standardError = stderr

            do {
                try process.run()
            } catch {
                fatalError("failed to run benchmark child process: \(error)")
            }
            process.waitUntilExit()

            if process.terminationStatus != 0 {
                let err = String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
                fatalError("benchmark child process failed: \(err)")
            }

            let data = stdout.fileHandleForReading.readDataToEndOfFile()
            let stdoutText = String(data: data, encoding: .utf8) ?? ""
            let fields = stdoutText.split(whereSeparator: \.isWhitespace)
            guard fields.count >= 2,
                  let elapsedUs = UInt64(fields[0]),
                  let auxMem = Int(fields[1]) else {
                fatalError("invalid child process output: \(stdoutText)")
            }

            totalTime += elapsedUs
            if elapsedUs > maxTime {
                maxTime = elapsedUs
            }

            totalMem += auxMem
            if auxMem > maxMem {
                maxMem = auxMem
            }
        }

        let avgTime = totalTime / UInt64(RUNS)
        // Memory is summed in bytes and converted to KiB once, after averaging.
        let avgMemKb = totalMem / RUNS / 1024
        let maxMemKb = maxMem / 1024

        let tableRow =
            "| \(padLeft(String(size), 10)) | " +
            "\(padLeft(formatSeconds(avgTime), 16)) | " +
            "\(padLeft(formatSeconds(maxTime), 16)) | " +
            "\(padLeft(String(avgMemKb), 20)) | " +
            "\(padLeft(String(maxMemKb), 20)) |"
        print(tableRow)
    }
}
SWIFT

RUN clang -O2 -fPIC -shared alloc_track.c -o liballoc_track.so -ldl

RUN swiftc -Ounchecked -whole-module-optimization \
    main.swift \
    -o swift-benchmark \
    -L. -lalloc_track \
    -Xlinker -rpath -Xlinker /app

ENV LD_PRELOAD=/app/liballoc_track.so
CMD ["./swift-benchmark"]
"""#
    try dockerfile.write(
        to: workdir.appendingPathComponent("Dockerfile"),
        atomically: true,
        encoding: .utf8
    )

    // Keeping build and run as separate child processes preserves Docker's
    // normal output and the original image tag used by the benchmark skill.
    try runCommand("docker", ["build", "-t", "swift-benchmark", workdir.path])
    try runCommand("docker", ["run", "--rm", "--init", "swift-benchmark"])
} catch {
    fputs("\(error)\n", stderr)
    exit(1)
}