|
| 1 | +// |
| 2 | +// _BenchmarkHost.swift |
| 3 | +// OpenSwiftUI |
| 4 | +// |
| 5 | +// Created by Kyle on 2023/1/9. |
| 6 | +// Lastest Version: iOS 15.5 |
| 7 | +// Status: Complete |
| 8 | +// ID: 3E629D505F0A70F29ACFC010AA42C6E0 |
| 9 | + |
| 10 | +#if canImport(Darwin) |
| 11 | +import CoreGraphics |
| 12 | +#elseif os(Linux) |
| 13 | +import Foundation |
| 14 | +#endif |
| 15 | + |
| 16 | +#if canImport(QuartzCore) |
| 17 | +import QuartzCore |
| 18 | +#endif |
| 19 | + |
| 20 | +private let enableProfiler = EnvironmentHelper.value(for: "OPENSWIFTUI_PROFILE_BENCHMARKS") |
| 21 | + |
| 22 | +public protocol _BenchmarkHost: AnyObject { |
| 23 | + func _renderForTest(interval: Double) |
| 24 | + func _renderAsyncForTest(interval: Double) -> Bool |
| 25 | + func _performScrollTest(startOffset: CGFloat, iterations: Int, delta: CGFloat, length: CGFloat, completion: (() -> Void)?) |
| 26 | +} |
| 27 | + |
| 28 | +extension _BenchmarkHost { |
| 29 | + public func _renderAsyncForTest(interval _: Double) -> Bool { |
| 30 | + false |
| 31 | + } |
| 32 | + |
| 33 | + public func _performScrollTest(startOffset _: CoreGraphics.CGFloat, iterations _: Int, delta _: CoreGraphics.CGFloat, length _: CoreGraphics.CGFloat, completion _: (() -> Void)?) {} |
| 34 | + |
| 35 | + public func measureAction(action: () -> Void) -> Double { |
| 36 | + #if canImport(QuartzCore) |
| 37 | + let begin = CACurrentMediaTime() |
| 38 | + if enableProfiler, |
| 39 | + let renderHost = self as? ViewRendererHost { |
| 40 | + renderHost.startProfiling() |
| 41 | + } |
| 42 | + action() |
| 43 | + let end = CACurrentMediaTime() |
| 44 | + if enableProfiler, |
| 45 | + let renderHost = self as? ViewRendererHost { |
| 46 | + renderHost.stopProfiling() |
| 47 | + } |
| 48 | + return end - begin |
| 49 | + #else |
| 50 | + fatalError("Unsupported Platfrom") |
| 51 | + #endif |
| 52 | + } |
| 53 | + |
| 54 | + public func measureRender(interval: Double = 1.0 / 60.0) -> Double { |
| 55 | + measureAction { |
| 56 | + _renderForTest(interval: interval) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public func measureRenders(seconds: Double) -> [Double] { |
| 61 | + measureRenders(duration: seconds) |
| 62 | + } |
| 63 | + |
| 64 | + public func measureRenders(duration: Double) -> [Double] { |
| 65 | + let minutes = duration / 60.0 |
| 66 | + let value = Int(minutes.rounded(.towardZero)) + 1 |
| 67 | + let count = max(value, 0) |
| 68 | + var results: [Double] = [] |
| 69 | + for _ in 0 ..< count { |
| 70 | + results.append(measureRender()) |
| 71 | + } |
| 72 | + return results |
| 73 | + } |
| 74 | +} |
0 commit comments