Sources/OrgApp/Perf.swift
85 lines · 3503 bytes
9 symbols in this file
1import Foundation
2import os
3
4/// Responsiveness messages for the debug console (subsystem `sh.krz.orgstar`, category
5/// `perf`): work that took longer than `threshold`, and stalls of the main thread. Times are
6/// wall-clock, so async work includes its waits. Measured work is also an interval in
7/// Instruments' os_signpost track.
8public enum Perf {
9 public static let log = Logger(subsystem: "sh.krz.orgstar", category: "perf")
10 static let signposter = OSSignposter(logger: log)
11 /// Work faster than this, about one frame, isn't logged.
12 public static let threshold = Duration.milliseconds(16)
13
14 @discardableResult
15 public static func measure<T>(_ name: StaticString, _ detail: @autoclosure () -> String = "", _ work: () throws -> T) rethrows -> T {
16 let state = signposter.beginInterval(name)
17 let start = ContinuousClock.now
18 defer {
19 signposter.endInterval(name, state)
20 report(name, ContinuousClock.now - start, detail())
21 }
22 return try work()
23 }
24
25 @discardableResult
26 public static func measure<T>(
27 _ name: StaticString, _ detail: @autoclosure () -> String = "", _ work: () async throws -> T
28 ) async rethrows -> T {
29 let state = signposter.beginInterval(name)
30 let start = ContinuousClock.now
31 defer {
32 signposter.endInterval(name, state)
33 report(name, ContinuousClock.now - start, detail())
34 }
35 return try await work()
36 }
37
38 /// Work timed from `Perf.begin` to `end`, for a function's whole body: `defer { interval.end() }`.
39 public struct Interval {
40 let name: StaticString
41 let state: OSSignpostIntervalState
42 let start = ContinuousClock.now
43
44 public func end(_ detail: @autoclosure () -> String = "") {
45 Perf.signposter.endInterval(name, state)
46 Perf.report(name, ContinuousClock.now - start, detail())
47 }
48 }
49
50 public static func begin(_ name: StaticString) -> Interval {
51 Interval(name: name, state: signposter.beginInterval(name))
52 }
53
54 static func report(_ name: StaticString, _ elapsed: Duration, _ detail: String) {
55 guard elapsed >= threshold else { return }
56 log.notice("\(String(describing: name), privacy: .public) took \(milliseconds(elapsed)) ms \(detail, privacy: .public)")
57 }
58
59 static func milliseconds(_ duration: Duration) -> Int {
60 Int(duration.components.seconds * 1000 + duration.components.attoseconds / 1_000_000_000_000_000)
61 }
62
63 nonisolated(unsafe) private static var watching = false
64
65 /// Logs each time the main thread takes `limit` or longer to run a block sent to it: a
66 /// tap or a frame waited that long. The messages before it say what ran.
67 public static func watchMainThread(limit: Duration = .milliseconds(100)) {
68 guard !watching else { return }
69 watching = true
70 let thread = Thread {
71 while true {
72 let sent = ContinuousClock.now
73 let done = DispatchSemaphore(value: 0)
74 DispatchQueue.main.async { done.signal() }
75 done.wait()
76 let waited = ContinuousClock.now - sent
77 if waited >= limit { log.error("main thread blocked for \(milliseconds(waited)) ms") }
78 Thread.sleep(forTimeInterval: 0.05)
79 }
80 }
81 thread.name = "Perf.watchMainThread"
82 thread.qualityOfService = .utility
83 thread.start()
84 }
85}