示例工程 24-performance-instruments

24-performance-instruments/Sources/Ch24Kit/Benchmark.swift

swift · 3.0 KB

import Foundation
 
/// 一次测量的结果:名字、中位数、校验和(防止优化掉计算)。
public struct Measurement: Sendable, Equatable {
    public let name: String
    public let median: Duration
    public let checksum: Int
 
    public init(name: String, median: Duration, checksum: Int) {
        self.name = name
        self.median = median
        self.checksum = checksum
    }
 
    /// 毫秒表示,便于打印与比较。
    public var milliseconds: Double {
        let components = median.components
        return Double(components.seconds) * 1_000
            + Double(components.attoseconds) / 1_000_000_000_000_000
    }
}
 
public enum Benchmark {
    /// 预热 + 多轮 + 中位数;返回校验和,测试可以断言结果未被优化掉。
    public static func measure(
        name: String,
        warmup: Int = 3,
        rounds: Int = 7,
        _ body: () -> Int
    ) -> Measurement {
        var checksum = 0
        for _ in 0..<warmup {
            checksum &+= body()
        }
        let clock = ContinuousClock()
        var samples: [Duration] = []
        for _ in 0..<rounds {
            samples.append(
                clock.measure {
                    checksum &+= body()
                })
        }
        samples.sort()
        let median = samples[samples.count / 2]
        return Measurement(name: name, median: median, checksum: checksum)
    }
}
 
/// 同一算法的三种写法,用于比较循环、reduce 与索引遍历。
public enum Algorithms {
    public static func sumLoop(_ values: [Int]) -> Int {
        var total = 0
        for value in values {
            total &+= value
        }
        return total
    }
 
    public static func sumReduce(_ values: [Int]) -> Int {
        values.reduce(0) { $0 &+ $1 }
    }
 
    public static func sumWhile(_ values: [Int]) -> Int {
        var total = 0
        var index = 0
        while index < values.count {
            total &+= values[index]
            index += 1
        }
        return total
    }
 
    public static func buildArray(_ count: Int, reserve: Bool) -> Int {
        var values: [Int] = []
        if reserve {
            values.reserveCapacity(count)
        }
        for value in 0..<count {
            values.append(value)
        }
        return values.capacity
    }
}
 
public enum Benchmarks {
    public static func run(iterations: Int = 1_000_000) -> [Measurement] {
        let values = Array(0..<iterations)
        let measurements = [
            Benchmark.measure(name: "sum-loop") { Algorithms.sumLoop(values) },
            Benchmark.measure(name: "sum-reduce") { Algorithms.sumReduce(values) },
            Benchmark.measure(name: "sum-while") { Algorithms.sumWhile(values) },
            Benchmark.measure(name: "append-reserve") {
                Algorithms.buildArray(iterations, reserve: true)
            },
            Benchmark.measure(name: "append-no-reserve") {
                Algorithms.buildArray(iterations, reserve: false)
            },
        ]
        return measurements.sorted { $0.name < $1.name }
    }
}