示例工程 52-app-performance-instruments
52-app-performance-instruments/Sources/Ch52Kit/Performance.swift
import Foundation
import SwiftUI
public enum Statistics {
public static func median(_ values: [Double]) -> Double? {
guard !values.isEmpty else { return nil }
let sorted = values.sorted()
let middle = sorted.count / 2
if sorted.count.isMultiple(of: 2) {
return (sorted[middle - 1] + sorted[middle]) / 2
}
return sorted[middle]
}
}
public struct BenchmarkResult: Sendable {
public let samples: [Double]
public let median: Double
public let minimum: Double
public let maximum: Double
}
public enum Benchmark {
/// 预热后取多轮中位数;输出只用于比较,不写进快照。
public static func run(
warmup: Int = 2,
iterations: Int = 5,
body: () -> Void
) -> BenchmarkResult {
for _ in 0..<max(0, warmup) {
body()
}
let clock = ContinuousClock()
var samples: [Double] = []
for _ in 0..<max(1, iterations) {
let duration = clock.measure { body() }
let components = duration.components
let seconds =
Double(components.seconds)
+ Double(components.attoseconds) / 1_000_000_000_000_000_000
samples.append(seconds)
}
return BenchmarkResult(
samples: samples,
median: Statistics.median(samples) ?? 0,
minimum: samples.min() ?? 0,
maximum: samples.max() ?? 0
)
}
}
/// 两种求和写法:预留容量与逐次追加。用于演示「测量而不是猜」。
public enum Workloads {
public static func appendWithoutReserve(_ count: Int) -> [Int] {
var values: [Int] = []
for index in 0..<count {
values.append(index)
}
return values
}
public static func appendWithReserve(_ count: Int) -> [Int] {
var values: [Int] = []
values.reserveCapacity(count)
for index in 0..<count {
values.append(index)
}
return values
}
public static func sum(_ count: Int) -> Int {
var total = 0
for index in 0..<count {
total &+= index
}
return total
}
}
/// 记录 `body` 求值次数,模拟 SwiftUI 的重算计数。
public final class BodyEvaluator: @unchecked Sendable {
public private(set) var count = 0
public init() {}
public func evaluate() {
count += 1
}
}
public struct CountedRow: View {
public let evaluator: BodyEvaluator
public init(evaluator: BodyEvaluator) {
self.evaluator = evaluator
}
public var body: some View {
evaluator.evaluate()
return Text("row")
}
}
/// 截图:性能分析流程。
public struct PerformanceBoard: View {
public init() {}
private let rows: [(String, String)] = [
("基线", "Release 构建,固定输入"),
("预热", "丢弃前几轮,避免冷启动"),
("采样", "多次取中位数,不看单次"),
("剖析", "Time Profiler / Allocations"),
("验证", "改一处,复测同一负载"),
("记录", "数字写进 expected/perf.txt"),
]
public var body: some View {
VStack(alignment: .leading, spacing: 9) {
Text("App 性能").font(.system(size: 17, weight: .semibold))
ForEach(rows, id: \.0) { row in
HStack(spacing: 10) {
Text(row.0)
.font(.system(size: 10, design: .monospaced))
.frame(width: 60, alignment: .leading)
Text(row.1)
.font(.system(size: 11))
.foregroundStyle(.secondary)
Spacer()
}
}
}
.padding(18)
.frame(width: 340, alignment: .leading)
.background(Color.white)
}
}