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.. 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.. [Measurement] { let values = Array(0..