Skip to content

Instantly share code, notes, and snippets.

@jessesquires
Created January 26, 2024 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessesquires/d46d8ee0891caccfa54eee28e1ff3565 to your computer and use it in GitHub Desktop.
Save jessesquires/d46d8ee0891caccfa54eee28e1ff3565 to your computer and use it in GitHub Desktop.
// 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