Created
January 26, 2024 22:19
-
-
Save jessesquires/d46d8ee0891caccfa54eee28e1ff3565 to your computer and use it in GitHub Desktop.
SwiftUI main thread hang detector: https://wadetregaskis.com/swiftui-main-thread-hang-detector/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://wadetregaskis.com/swiftui-main-thread-hang-detector/ | |
var body: some View { | |
SomeRootView { | |
… | |
}.task { | |
let approximateGranularity = Duration.milliseconds(10) | |
let threshold = Duration.milliseconds(50) | |
let clock = SuspendingClock() | |
var lastIteration = clock.now | |
while !Task.isCancelled { | |
try? await Task.sleep(for: approximateGranularity, | |
tolerance: approximateGranularity / 2, | |
clock: clock) | |
let now = clock.now | |
if now - lastIteration > threshold { | |
print("Main thread hung for \((now - lastIteration).formatted(.units(width: .wide, fractionalPart: .show(length: 2)))).") | |
} | |
lastIteration = now | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment