Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import Darwinimport Foundation
enum LivePerformanceScenario: String, CaseIterable, Codable { case swap = "swap-2-windows" case layout10 = "layout-change-10" case layout30 = "layout-change-30" case hotkey = "hotkey-focus-move" case slow = "slow-neighbour" case newWindow = "new-window-to-tile"
func selected(environment: [String: String] = ProcessInfo.processInfo.environment) throws -> Bool { try validatePerformanceScenarioSelection(environment: environment) return environment["PARCEL_SMOOTHNESS_SCENARIO"].map { $0 == rawValue } ?? true }}
func validatePerformanceScenarioSelection(environment: [String: String]) throws { if let value = environment["PARCEL_SMOOTHNESS_SCENARIO"], LivePerformanceScenario(rawValue: value) == nil { throw E2EError(description: "Unknown PARCEL_SMOOTHNESS_SCENARIO: \(value)") }}
struct PerformanceQuietState: Codable { let eligible: Bool let loadAverage: Double let acPower: Bool let thermalWarning: Bool let maximumProcessCPU: Double let lowPowerMode: Bool let reasons: [String]
static func load(environment: [String: String] = ProcessInfo.processInfo.environment) throws -> Self? { guard let path = environment["PARCEL_BENCH_QUIET"] else { return nil } return try JSONDecoder().decode(Self.self, from: Data(contentsOf: URL(fileURLWithPath: path))) }}
enum PerformanceArtifacts { static var host: String { ProcessInfo.processInfo.hostName.map { $0.isLetter || $0.isNumber || $0 == "-" ? $0 : "-" } .reduce(into: "") { $0.append($1) } }
static func directory(_ area: String) throws -> URL { let root = ProcessInfo.processInfo.environment["PARCEL_PERF_OUTPUT"].map { URL(fileURLWithPath: $0) } ?? repositoryRoot().appendingPathComponent("build") let directory = root.appendingPathComponent(area, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) return directory }
@discardableResult static func write<Value: Encodable>(_ value: Value, area: String, name: String) throws -> URL { let url = try directory(area).appendingPathComponent(name) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(value).write(to: url, options: .atomic) return url }}
enum ProcessPerformanceCounterError: Error, Equatable { case timebaseUnavailable(kern_return_t) case invalidTimebase(numerator: UInt32, denominator: UInt32) case cpuTimeOverflow}
struct ProcessPerformanceCounters: Codable, Equatable { let cpuNanoseconds: UInt64 let instructions: UInt64 let interruptWakeups: UInt64 let packageIdleWakeups: UInt64 let physicalFootprint: UInt64
static func read(pid: pid_t) throws -> Self { var usage = rusage_info_v4() let result = withUnsafeMutablePointer(to: &usage) { pointer in pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V4, $0) } } guard result == 0 else { throw E2EError(description: "Process counters unavailable for \(pid): errno \(errno)") } var timebase = mach_timebase_info_data_t() let timebaseResult = mach_timebase_info(&timebase) guard timebaseResult == KERN_SUCCESS else { throw ProcessPerformanceCounterError.timebaseUnavailable(timebaseResult) } return Self( cpuNanoseconds: try cpuTimeNanoseconds( userTicks: usage.ri_user_time, systemTicks: usage.ri_system_time, numerator: timebase.numer, denominator: timebase.denom), instructions: usage.ri_instructions, interruptWakeups: usage.ri_interrupt_wkups, packageIdleWakeups: usage.ri_pkg_idle_wkups, physicalFootprint: usage.ri_phys_footprint) }
static func cpuTimeNanoseconds( userTicks: UInt64, systemTicks: UInt64, numerator: UInt32, denominator: UInt32 ) throws(ProcessPerformanceCounterError) -> UInt64 { guard numerator > 0, denominator > 0 else { throw .invalidTimebase(numerator: numerator, denominator: denominator) } let (ticks, overflow) = userTicks.addingReportingOverflow(systemTicks) guard !overflow else { throw .cpuTimeOverflow } let product = ticks.multipliedFullWidth(by: UInt64(numerator)) let divisor = UInt64(denominator) guard product.high < divisor else { throw .cpuTimeOverflow } return divisor.dividingFullWidth(product).quotient }
@inline(never) static func verifyInstructionCounter() throws { let before = try read(pid: getpid()) var total: UInt64 = 0 for value in 0..<100_000 { total &+= UInt64(value) &* 17 } guard total == 84_999_150_000, try read(pid: getpid()).instructions > before.instructions else { throw E2EError( description: "Public retired-instruction counter unavailable; idle instructions cannot be gated") } }
func delta(from previous: Self) throws -> Self { guard cpuNanoseconds >= previous.cpuNanoseconds, instructions >= previous.instructions, interruptWakeups >= previous.interruptWakeups, packageIdleWakeups >= previous.packageIdleWakeups else { throw E2EError(description: "Process performance counters moved backwards") } return Self( cpuNanoseconds: cpuNanoseconds - previous.cpuNanoseconds, instructions: instructions - previous.instructions, interruptWakeups: interruptWakeups - previous.interruptWakeups, packageIdleWakeups: packageIdleWakeups - previous.packageIdleWakeups, physicalFootprint: physicalFootprint) }
var idleBudgetFailures: [String] { var failures: [String] = [] if cpuNanoseconds >= 5_000_000 { failures.append("CPU time must be <5 ms: \(cpuNanoseconds) ns") } if instructions >= 5_000_000 { failures.append("Instructions must be <5M: \(instructions)") } if interruptWakeups > 2 { failures.append("Interrupt wakeups must be <=2: \(interruptWakeups)") } if packageIdleWakeups > 2 { failures.append("Package idle wakeups must be <=2: \(packageIdleWakeups)") } return failures }}
struct FootprintSample: Codable, Equatable { let commands: Int let bytes: UInt64}
func footprintSlope(_ samples: [FootprintSample]) throws -> Double { guard samples.count >= 2, zip(samples, samples.dropFirst()).allSatisfy({ $0.commands < $1.commands }) else { throw E2EError(description: "Footprint regression needs ordered distinct command samples") } let count = Double(samples.count) let meanX = samples.reduce(0) { $0 + Double($1.commands) } / count let meanY = samples.reduce(0) { $0 + Double($1.bytes) } / count let numerator = samples.reduce(0) { $0 + (Double($1.commands) - meanX) * (Double($1.bytes) - meanY) } let denominator = samples.reduce(0) { $0 + pow(Double($1.commands) - meanX, 2) } return numerator / denominator}
func soakBudgetFailures(finalBytes: UInt64, slope: Double) -> [String] { var failures: [String] = [] if finalBytes >= 40_000_000 { failures.append("Final physical footprint must be <40 MB: \(finalBytes) bytes") } if !slope.isFinite || slope >= 8_192 { failures.append("Last10-sample slope must be <8 KiB/command: \(slope)") } return failures}