ウィキソートで配列を並び替える
ウィキソートを使用する
ウィキソート (wiki sort) は、ボトムアップのマージソートの枠組みで、大きな区間同士をマージするときに配列内の小さなバッファと回転を組み合わせるブロックマージである。最悪計算量 \(O(n \log n)\) の安定ソートで、マージソートのように \(O(n)\) の追加配列に頼らない実装を目指す。
- 初期整列: 長さ 4〜8 程度の小さな区間を安定ソートであるソートネットワーク(または挿入ソート)で整える。
- レベルごとのマージ: 隣接する整列済み部分列
(A, B)のペアを区間長が配列全体になるまで段階的に倍化していく。 - キャッシュマージ: 部分列がキャッシュ(例: 512 要素)に収まるレベルではキャッシュへ退避してマージする。
- 大きなレベルのマージ: それより大きいレベルでは、本番のウィキソートは区間長の平方根程度のブロック分割と内部バッファによるタグ付けでマージする。計測コードでは固定キャッシュに収まらない側を回転で分割し、片側がキャッシュに収まるまで再帰する回転ベースのマージで代用する(補助記憶は \(O(1)\) のまま)。
- バッファの復元: 一時的に退避した内部バッファを挿入ソートと再配置で元の位置へ戻す(本番のブロックマージ経路)。
procedure wiki_sort(A)
if length(A) < 4 then
insertion_sort(A)
return
sort_runs_of_size_4_to_8(A)
level = 4
while level < length(A)
for each adjacent pair (A_part, B_part) of sorted runs of length level
if A_part fits in fixed_cache then
merge_with_cache(A_part, B_part, fixed_cache)
else
rotate_merge_in_place(A_part, B_part, fixed_cache)
level = next_merge_level(level)
実装は回転とブロック操作が多く、マージソート単体よりコード量は増えるが、固定キャッシュ(例: 512 要素)と回転ベースのインプレースマージにより補助記憶を \(O(1)\) に抑えた安定整列を実現する。
類似アルゴリズムとの相違点
グレイルソート・コタソートと並ぶブロックマージ系で、ウィキソートはマージと同時にブロック選択を行い、追加配列を抑えた \(O(1)\) 補助記憶の安定整列を実現する。
時間計算量および空間計算量を計測する
| Size | Average time (s) | Maximum time (s) | Average memory (KiB) | Maximum memory (KiB) |
|---|---|---|---|---|
| 256 | 0.000006 | 0.000067 | 0 | 0 |
| 512 | 0.000013 | 0.000076 | 0 | 0 |
| 1024 | 0.000030 | 0.000345 | 0 | 0 |
| 2048 | 0.000072 | 0.000919 | 0 | 0 |
| 4096 | 0.000142 | 0.000212 | 0 | 0 |
| 8192 | 0.000309 | 0.000459 | 0 | 0 |
| 16384 | 0.000678 | 0.000954 | 0 | 0 |
| 32768 | 0.001477 | 0.009821 | 0 | 0 |
| 65536 | 0.003217 | 0.011972 | 0 | 0 |
| 131072 | 0.007014 | 0.025977 | 0 | 0 |
| 262144 | 0.016251 | 0.054867 | 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
let CACHE_SIZE: Int = 512
struct WikiRange {
var start: Int
var end: Int
init(_ start: Int, _ end: Int) {
self.start = start
self.end = end
}
func len() -> Int {
end - start
}
}
final class WikiIterator {
var size: Int
var power_of_two: Int
var numerator: Int
var decimal: Int
var denominator: Int
var decimal_step: Int
var numerator_step: Int
init(_ size: Int, _ min_level: Int) {
let power_of_two = floor_power_of_two(size)
let denominator = power_of_two / min_level
self.size = size
self.power_of_two = power_of_two
self.numerator = 0
self.decimal = 0
self.denominator = denominator
self.decimal_step = size / denominator
self.numerator_step = size % denominator
}
func begin() {
numerator = 0
decimal = 0
}
func next_range() -> WikiRange {
let start = decimal
decimal += decimal_step
numerator += numerator_step
if numerator >= denominator {
numerator -= denominator
decimal += 1
}
return WikiRange(start, decimal)
}
func finished() -> Bool {
decimal >= size
}
func next_level() -> Bool {
decimal_step += decimal_step
numerator_step += numerator_step
if numerator_step >= denominator {
numerator_step -= denominator
decimal_step += 1
}
return decimal_step < size
}
func length() -> Int {
decimal_step
}
}
func floor_power_of_two(_ value: Int) -> Int {
var x = value
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
if Int.bitWidth >= 64 {
x |= x >> 32
}
return x - (x >> 1)
}
func wiki_insertion_sort(_ a: UnsafeMutableBufferPointer<Int>, _ range: WikiRange) {
for i in (range.start + 1)..<range.end {
let temp = a[i]
var j = i
while j > range.start && temp < a[j - 1] {
a[j] = a[j - 1]
j -= 1
}
a[j] = temp
}
}
func wiki_reverse(_ a: UnsafeMutableBufferPointer<Int>, _ range: WikiRange) {
let len = range.len()
for index in (0..<(len / 2)).reversed() {
a.swapAt(range.start + index, range.end - index - 1)
}
}
func wiki_copy_within(_ a: UnsafeMutableBufferPointer<Int>, _ srcStart: Int, _ srcEnd: Int, _ dest: Int) {
let count = srcEnd - srcStart
if dest <= srcStart {
for i in 0..<count {
a[dest + i] = a[srcStart + i]
}
} else {
for i in (0..<count).reversed() {
a[dest + i] = a[srcStart + i]
}
}
}
func wiki_rotate(
_ a: UnsafeMutableBufferPointer<Int>,
_ amount: Int,
_ range: WikiRange,
_ cache: UnsafeMutableBufferPointer<Int>,
_ cache_size: Int
) {
if range.len() == 0 {
return
}
let split = range.start + amount
let range1 = WikiRange(range.start, split)
let range2 = WikiRange(split, range.end)
if range1.len() <= range2.len() {
if range1.len() <= cache_size {
for i in 0..<range1.len() {
cache[i] = a[range1.start + i]
}
wiki_copy_within(a, range2.start, range2.end, range1.start)
let dest = range1.start + range2.len()
for i in 0..<range1.len() {
a[dest + i] = cache[i]
}
return
}
} else if range2.len() <= cache_size {
for i in 0..<range2.len() {
cache[i] = a[range2.start + i]
}
wiki_copy_within(a, range1.start, range1.end, range2.end - range1.len())
for i in 0..<range2.len() {
a[range1.start + i] = cache[i]
}
return
}
wiki_reverse(a, range1)
wiki_reverse(a, range2)
wiki_reverse(a, range)
}
func merge_into(
_ from: UnsafeMutableBufferPointer<Int>,
_ a: WikiRange,
_ b: WikiRange,
_ into: UnsafeMutableBufferPointer<Int>
) {
var a_index = a.start
var b_index = b.start
var insert = 0
while true {
if from[b_index] >= from[a_index] {
into[insert] = from[a_index]
a_index += 1
insert += 1
if a_index == a.end {
for i in 0..<(b.end - b_index) {
into[insert + i] = from[b_index + i]
}
break
}
} else {
into[insert] = from[b_index]
b_index += 1
insert += 1
if b_index == b.end {
for i in 0..<(a.end - a_index) {
into[insert + i] = from[a_index + i]
}
break
}
}
}
}
func merge_external(
_ a: UnsafeMutableBufferPointer<Int>,
_ a_range: WikiRange,
_ b: WikiRange,
_ cache: UnsafeMutableBufferPointer<Int>
) {
for i in 0..<a_range.len() {
cache[i] = a[a_range.start + i]
}
var a_index = 0
var b_index = b.start
var insert = a_range.start
let a_last = a_range.len()
let b_last = b.end
if b.len() > 0 && a_range.len() > 0 {
while true {
if a[b_index] >= cache[a_index] {
a[insert] = cache[a_index]
a_index += 1
insert += 1
if a_index == a_last {
break
}
} else {
a[insert] = a[b_index]
b_index += 1
insert += 1
if b_index == b_last {
break
}
}
}
}
for i in 0..<(a_last - a_index) {
a[insert + i] = cache[a_index + i]
}
}
/// Backward merge when the right run fits in `cache`.
func merge_external_right(
_ a: UnsafeMutableBufferPointer<Int>,
_ a_range: WikiRange,
_ b: WikiRange,
_ cache: UnsafeMutableBufferPointer<Int>
) {
let right_len = b.len()
for i in 0..<right_len {
cache[i] = a[b.start + i]
}
var i = a_range.end
var j = right_len
var k = b.end
while i > a_range.start && j > 0 {
if a[i - 1] > cache[j - 1] {
k -= 1
i -= 1
a[k] = a[i]
} else {
k -= 1
j -= 1
a[k] = cache[j]
}
}
while j > 0 {
k -= 1
j -= 1
a[k] = cache[j]
}
}
/// First index `i` in `a[start..<start+length]` with `a[i] >= target`.
func binary_search_left(
_ a: UnsafeMutableBufferPointer<Int>,
_ start: Int,
_ length: Int,
_ target: Int
) -> Int {
var left = 0
var right = length
while left < right {
let middle = left + ((right - left) / 2)
if a[start + middle] < target {
left = middle + 1
} else {
right = middle
}
}
return left
}
/// Stable in-place merge via binary search + rotate, using the fixed cache when
/// either run fits (no O(n) heap buffer).
func merge_in_place(
_ a: UnsafeMutableBufferPointer<Int>,
_ a_range: WikiRange,
_ b: WikiRange,
_ cache: UnsafeMutableBufferPointer<Int>,
_ cache_size: Int
) {
let left_len = a_range.len()
let right_len = b.len()
if left_len == 0 || right_len == 0 {
return
}
if a[a_range.end - 1] <= a[b.start] {
return
}
if left_len <= cache_size {
merge_external(a, a_range, b, cache)
return
}
if right_len <= cache_size {
merge_external_right(a, a_range, b, cache)
return
}
let rblock = left_len / 2
let lblock = left_len - rblock
let center = a[a_range.start + lblock]
let left = binary_search_left(a, b.start, right_len, center)
let right = right_len - left
if left > 0 {
// [ lblock | rblock | left | right ] → rotate middle band
wiki_rotate(
a,
rblock,
WikiRange(a_range.start + lblock, a_range.start + lblock + rblock + left),
cache,
cache_size
)
// Now: [ lblock | left | rblock | right ]
merge_in_place(
a,
WikiRange(a_range.start, a_range.start + lblock),
WikiRange(a_range.start + lblock, a_range.start + lblock + left),
cache,
cache_size
)
merge_in_place(
a,
WikiRange(a_range.start + lblock + left, a_range.start + lblock + left + rblock),
WikiRange(
a_range.start + lblock + left + rblock,
a_range.start + lblock + left + rblock + right
),
cache,
cache_size
)
} else if right > 0 {
merge_in_place(
a,
WikiRange(a_range.start + lblock, a_range.end),
b,
cache,
cache_size
)
}
}
func merge_pair(
_ a: UnsafeMutableBufferPointer<Int>,
_ a_range: WikiRange,
_ b: WikiRange,
_ cache: UnsafeMutableBufferPointer<Int>,
_ cache_size: Int
) {
if a[b.end - 1] < a[a_range.start] {
wiki_rotate(
a,
a_range.len(),
WikiRange(a_range.start, b.end),
cache,
cache_size
)
} else if a[b.start] < a[a_range.end - 1] {
if a_range.len() <= cache_size {
merge_external(a, a_range, b, cache)
} else {
merge_in_place(a, a_range, b, cache, cache_size)
}
}
}
func wiki_sort(_ a: inout [Int]) {
a.withUnsafeMutableBufferPointer { wiki_sort($0) }
}
func wiki_sort(_ a: UnsafeMutableBufferPointer<Int>) {
let size = a.count
var cacheStorage = [Int](repeating: 0, count: CACHE_SIZE)
let cache_size = CACHE_SIZE
cacheStorage.withUnsafeMutableBufferPointer { cache in
if size < 4 {
if size == 3 {
if a[1] < a[0] {
a.swapAt(0, 1)
}
if a[2] < a[1] {
a.swapAt(1, 2)
if a[1] < a[0] {
a.swapAt(0, 1)
}
}
} else if size == 2 && a[1] < a[0] {
a.swapAt(0, 1)
}
return
}
let iterator = WikiIterator(size, 4)
iterator.begin()
while !iterator.finished() {
let range = iterator.next_range()
wiki_insertion_sort(a, range)
}
if size < 8 {
return
}
while true {
if iterator.length() < cache_size {
if (iterator.length() + 1) * 4 <= cache_size && iterator.length() * 4 <= size {
iterator.begin()
while !iterator.finished() {
let a1 = iterator.next_range()
let b1 = iterator.next_range()
let a2 = iterator.next_range()
let b2 = iterator.next_range()
var merged1_len = 0
var merged2_len = 0
if a[b1.end - 1] < a[a1.start] {
for i in 0..<a1.len() {
cache[b1.len() + i] = a[a1.start + i]
}
for i in 0..<b1.len() {
cache[i] = a[b1.start + i]
}
merged1_len = a1.len() + b1.len()
} else if a[b1.start] < a[a1.end - 1] {
merge_into(a, a1, b1, cache)
merged1_len = a1.len() + b1.len()
} else if !(a[b2.start] < a[a2.end - 1]) && !(a[a2.start] < a[b1.end - 1]) {
continue
} else {
for i in 0..<a1.len() {
cache[i] = a[a1.start + i]
}
for i in 0..<b1.len() {
cache[a1.len() + i] = a[b1.start + i]
}
merged1_len = a1.len() + b1.len()
}
let a1Merged = WikiRange(a1.start, b1.end)
if a[b2.end - 1] < a[a2.start] {
for i in 0..<a2.len() {
cache[merged1_len + b2.len() + i] = a[a2.start + i]
}
for i in 0..<b2.len() {
cache[merged1_len + i] = a[b2.start + i]
}
merged2_len = a2.len() + b2.len()
} else if a[b2.start] < a[a2.end - 1] {
let cacheTail = UnsafeMutableBufferPointer(rebasing: cache[merged1_len...])
merge_into(a, a2, b2, cacheTail)
merged2_len = a2.len() + b2.len()
} else {
for i in 0..<a2.len() {
cache[merged1_len + i] = a[a2.start + i]
}
for i in 0..<b2.len() {
cache[merged1_len + a2.len() + i] = a[b2.start + i]
}
merged2_len = a2.len() + b2.len()
}
let a3 = WikiRange(0, merged1_len)
let b3 = WikiRange(merged1_len, merged1_len + merged2_len)
if cache[b3.end - 1] < cache[a3.start] {
for i in 0..<merged1_len {
a[a1Merged.start + merged2_len + i] = cache[a3.start + i]
}
for i in 0..<merged2_len {
a[a1Merged.start + i] = cache[b3.start + i]
}
} else if cache[b3.start] < cache[a3.end - 1] {
let into = UnsafeMutableBufferPointer(
rebasing: a[a1Merged.start..<(a1Merged.start + merged1_len + merged2_len)]
)
merge_into(cache, a3, b3, into)
} else {
for i in 0..<merged1_len {
a[a1Merged.start + i] = cache[a3.start + i]
}
for i in 0..<merged2_len {
a[a1Merged.start + merged1_len + i] = cache[b3.start + i]
}
}
}
_ = iterator.next_level()
} else {
iterator.begin()
while !iterator.finished() {
let a_range = iterator.next_range()
let b = iterator.next_range()
merge_pair(a, a_range, b, cache, cache_size)
}
}
} else {
iterator.begin()
while !iterator.finished() {
let a_range = iterator.next_range()
let b = iterator.next_range()
merge_pair(a, a_range, b, cache, cache_size)
}
}
if !iterator.next_level() {
break
}
}
}
}
func benchmark_sort(_ array: inout [Int]) {
wiki_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)
}