Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Benchmark/TranscriptBench/BenchApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import SwiftUI
/// -hold 1 stay open after the run instead of exiting
/// -noTail 1 TranscriptKit draws the growing end on the main thread, as before
/// -mode scroll scroll through the history instead of streaming
/// -mode many replace the documents of many texts at once (see `ManyTextsModel`)
/// -scrollSeconds <s> how long to scroll (default 10)
/// -scrollSpeed <pt/s> scrolling speed (default 3000)
/// -corpus rich stream `Corpus.richSection` text instead of the default
Expand Down Expand Up @@ -326,6 +327,16 @@ private extension WebRenderer {
}

struct BenchRoot: View {
var body: some View {
if UserDefaults.standard.string(forKey: "mode") == "many" {
ManyTextsRenderer()
} else {
BenchRendererRoot()
}
}
}

struct BenchRendererRoot: View {
@State private var model = BenchModel()

var body: some View {
Expand Down
159 changes: 159 additions & 0 deletions Benchmark/TranscriptBench/ManyTexts.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import SwiftUI
@_spi(Diagnostics) import TranscriptKit

/// `-mode many`: a page of many texts that all get a new long document in the
/// same main-thread turn, while a stream at the top of the page gets a short
/// chunk. Each round prints one `MANY_RESULT {json}` line, then the app exits.
///
/// Launch arguments:
/// -views <n> texts on the page (default 20)
/// -chars <n> length of each new document (default 6000)
/// -rounds <n> rounds, each with new documents (default 5)
@MainActor
@Observable
final class ManyTextsModel {
private(set) var documents: [TranscriptDocument]
@ObservationIgnored let stream = TranscriptStream(markdown: "The stream at the top of the page.")
@ObservationIgnored private let views: Int
@ObservationIgnored private let characters: Int
@ObservationIgnored private let rounds: Int

init() {
let defaults = UserDefaults.standard
views = defaults.object(forKey: "views") != nil ? max(defaults.integer(forKey: "views"), 1) : 20
characters = defaults.object(forKey: "chars") != nil ? defaults.integer(forKey: "chars") : 6000
rounds = defaults.object(forKey: "rounds") != nil ? max(defaults.integer(forKey: "rounds"), 1) : 5
documents = (0..<views).map { MarkdownStreamParser.document(from: "Text \($0).", idPrefix: "start\($0)") }
}

func run() async {
try? await Task.sleep(for: .seconds(2))
for round in 1...rounds {
await measure(round: round)
try? await Task.sleep(for: .seconds(1))
}
if !UserDefaults.standard.bool(forKey: "hold") { exit(0) }
}

/// One round. The new documents are parsed before the round starts, so
/// that the round measures layout only.
private func measure(round: Int) async {
let next = (0..<views).map { index in
let markdown = String(Corpus.response(characters: characters, startingAt: round * 1000 + index * 10))
return MarkdownStreamParser.document(from: markdown, idPrefix: "r\(round)v\(index)")
}
let threadsBefore = ThreadSampler.count()
let sampler = ThreadSampler()
sampler.start()
let monitor = FrameMonitor()
monitor.start()
TranscriptDiagnostics.reset()
let streamBefore = stream.document

let start = ContinuousClock.now
documents = next
stream.append(" Round \(round) adds **short** text.")
var parseMs: Double?
var allInstalledMs: Double?
// The stream's view installs its update too.
while parseMs == nil || allInstalledMs == nil, ContinuousClock.now - start < .seconds(20) {
try? await Task.sleep(for: .milliseconds(1))
let elapsed = (ContinuousClock.now - start).milliseconds
if parseMs == nil, stream.document != streamBefore { parseMs = elapsed }
if allInstalledMs == nil, TranscriptDiagnostics.current.installs >= views + 1 { allInstalledMs = elapsed }
}
try? await Task.sleep(for: .milliseconds(500))
let frames = monitor.stop()
let threadsPeak = sampler.stop()

let result = ManyResult(
round: round, views: views, characters: characters, cores: ProcessInfo.processInfo.activeProcessorCount,
threadsBefore: threadsBefore, threadsPeak: threadsPeak, streamParseMs: parseMs, allInstalledMs: allInstalledMs,
installs: TranscriptDiagnostics.current.installs, worstFrameMs: frames.worstFrameMs,
droppedFrames: frames.droppedFrames, osVersion: UIDevice.current.systemVersion
)
let json = String(data: try! JSONEncoder().encode(result), encoding: .utf8)!
print("MANY_RESULT \(json)")
fflush(stdout)
}
}

struct ManyResult: Codable {
var round: Int
var views: Int
var characters: Int
var cores: Int
/// Threads of the process before the round, and the most during it.
var threadsBefore: Int
var threadsPeak: Int
/// From the new documents to the stream's parse of the short chunk on
/// the main thread. It includes the wait for the next display frame.
var streamParseMs: Double?
/// From the new documents until every text has installed a layout.
var allInstalledMs: Double?
var installs: Int
/// The longest main-thread frame of the round.
var worstFrameMs: Double
var droppedFrames: Int
var osVersion: String
}

/// Samples the thread count of the process every 2 ms, on a thread of its
/// own, and keeps the highest.
final class ThreadSampler: @unchecked Sendable {
private let lock = NSLock()
private var peak = 0
private var running = true

func start() {
let thread = Thread { [self] in
while lock.withLock({ running }) {
let count = Self.count()
lock.withLock { peak = max(peak, count) }
usleep(2000)
}
}
thread.qualityOfService = .userInteractive
thread.start()
}

func stop() -> Int {
lock.withLock {
running = false
return peak
}
}

static func count() -> Int {
var threads: thread_act_array_t?
var count: mach_msg_type_number_t = 0
guard task_threads(mach_task_self_, &threads, &count) == KERN_SUCCESS, let threads else { return 0 }
for index in 0..<Int(count) { mach_port_deallocate(mach_task_self_, threads[index]) }
vm_deallocate(mach_task_self_, vm_address_t(UInt(bitPattern: threads)),
vm_size_t(Int(count) * MemoryLayout<thread_t>.stride))
return Int(count)
}
}

private extension Duration {
var milliseconds: Double {
Double(components.seconds) * 1000 + Double(components.attoseconds) / 1e15
}
}

struct ManyTextsRenderer: View {
@State private var model = ManyTextsModel()

var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
TranscriptText(stream: model.stream)
ForEach(model.documents.indices, id: \.self) { index in
TranscriptText(model.documents[index])
}
}
.padding(16)
}
.task { await model.run() }
}
}
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
markup is held back for a character or two, so what is on screen almost never changes style or shrinks.
- **Off the main thread.** Each frame's chunks are parsed on a background queue and laid out on another. Only the
blocks that changed are laid out again, and the line being written is drawn on the layout queue into a surface.
The main thread installs the result and redraws what changed.
The main thread installs the result and redraws what changed. All streams and views share the system's pool of
threads, with about one thread for each processor core. At most one long layout for each core runs at a time, also
when a layout waits, for example while a font loads the first time. So a screen that shows many texts at once does
not start a thread for each of them. Short work, such as the parse and layout of streamed text, goes ahead of the
long layouts of other views.
- **One selectable document.** The whole text is one view with the system's selection handles, loupe and edit menu,
and a selection can run from one block to the next: across headings, paragraphs, lists and code blocks.
- **Markdown:**
Expand Down
67 changes: 56 additions & 11 deletions Sources/TranscriptKit/Layout/LayoutEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ import QuartzCore
/// first layout, a change of width or style, and a replaced document when
/// the view's `replacementCrossfadeDuration` asks for it. It does so through
/// `queue.sync`, so the engine's state is only ever touched on its queue.
/// When the queue is idle, the main thread does that work itself and does
/// not wait for a thread. The queue shares its threads with the queues of
/// all other views and streams (see `WorkQueue`). A drain of short work,
/// such as text added to the end, goes ahead of the long layouts of other
/// views. A long drain waits for its turn among the long layouts of all
/// views; a `sync` call does not wait for that turn.
///
/// While text is being appended, the engine also draws the end of the
/// document into a surface (see `TailRenderer`), which travels with the
Expand Down Expand Up @@ -79,7 +85,7 @@ final class LayoutEngine: @unchecked Sendable {
}
}

let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated)
let queue = WorkQueue.serial(label: "TranscriptKit.layout")
/// The work in flight: drains that are scheduled or running, a result
/// that the view has not taken yet, and the image store's loads.
let work: PendingWork
Expand All @@ -98,6 +104,14 @@ final class LayoutEngine: @unchecked Sendable {
/// `pending` waits for `relayout` on the main thread: a drain leaves it.
private var pendingIsForMain = false
private var drainScheduled = false
/// The scheduled drain goes ahead of the long work of other views.
private var drainIsUrgent = false
/// Identifies the scheduled drain. An older drain that runs later, as a
/// long drain can, leaves the schedule alone.
private var drainID = 0
/// The document of the newest layout, or of the one the queue makes
/// next. A document that only adds a little to it is short work.
private var laidOut = TranscriptDocument()
/// Layouts are made at most this often: a document that arrives sooner
/// waits, and is replaced by any newer one that arrives meanwhile. More
/// than one layout per display frame would never be seen.
Expand Down Expand Up @@ -241,6 +255,7 @@ final class LayoutEngine: @unchecked Sendable {
pendingIsForMain = false
mailbox = nil
onOutput = nil
laidOut = TranscriptDocument()
}
queue.async {
self.base = nil
Expand All @@ -264,7 +279,8 @@ final class LayoutEngine: @unchecked Sendable {
@discardableResult
func submit(_ request: Request, schedulesLayout: Bool = true) -> Bool {
var accepted = true
let delay: CFTimeInterval? = lock.withLock {
let urgent = Self.isShortWork(request.document, after: lock.withLock { laidOut })
let schedule: (delay: CFTimeInterval, urgent: Bool, id: Int)? = lock.withLock {
guard !isShutDown else { accepted = false; return nil }
guard request.source >= currentSource else { return nil }
if request.source > currentSource {
Expand All @@ -275,21 +291,43 @@ final class LayoutEngine: @unchecked Sendable {
lastSequence = request.sequence
pending = request
pendingIsForMain = !schedulesLayout
if drainScheduled || !schedulesLayout { return nil }
if !schedulesLayout { return nil }
// A drain that is not urgent can wait behind the work of other
// views, so short work schedules an urgent one of its own. The
// drain that runs first takes the request.
if drainScheduled, drainIsUrgent || !urgent { return nil }
drainScheduled = true
return max(lastDrain + frameInterval - CACurrentMediaTime(), 0)
drainIsUrgent = urgent
drainID += 1
return (max(lastDrain + frameInterval - CACurrentMediaTime(), 0), urgent, drainID)
}
if let delay {
if let schedule {
let id = schedule.id
work.begin()
if delay > 0 {
queue.asyncAfter(deadline: .now() + delay) { self.drain(); self.work.end() }
if schedule.urgent {
WorkQueue.async(queue, urgent: true, after: schedule.delay) { self.drain(id); self.work.end() }
} else {
queue.async { self.drain(); self.work.end() }
WorkQueue.asyncLong(queue, after: schedule.delay) { self.drain(id); self.work.end() }
}
}
return accepted
}

/// Whether laying out `document` takes about a millisecond or less: its
/// text is short, or it adds only a little text to the end of `laidOut`,
/// whose layout it reuses. An urgent drain keeps its QoS when a longer
/// document replaces the waiting one.
private static func isShortWork(_ document: TranscriptDocument, after laidOut: TranscriptDocument) -> Bool {
let length = document.utf16Count
if length <= WorkQueue.shortLength { return true }
// Documents that share no storage, as when the app parses each
// version itself, would compare every block. A stream shares all
// but its last block or two.
guard laidOut.count > 0, length - laidOut.utf16Count <= WorkQueue.shortLength,
laidOut.count - document.knownSharedPrefix(with: laidOut) <= 8 else { return false }
return document.extends(laidOut)
}

private func takePending() -> Request? {
lock.withLock { () -> Request? in
defer {
Expand All @@ -311,12 +349,18 @@ final class LayoutEngine: @unchecked Sendable {

/// Lays out the newest waiting document. One that arrives while this
/// works schedules its own drain, a frame after this one started.
private func drain() {
///
/// - Parameter id: the drain's `drainID`, or nil to end the schedule.
private func drain(_ id: Int? = nil) {
let next: Request? = lock.withLock {
drainScheduled = false
if id == nil || id == drainID {
drainScheduled = false
drainIsUrgent = false
}
guard let request = pending, !pendingIsForMain else { return nil }
pending = nil
lastDrain = CACurrentMediaTime()
if width > 0 { laidOut = request.document }
return request
}
guard let request = next else { return }
Expand Down Expand Up @@ -441,7 +485,7 @@ final class LayoutEngine: @unchecked Sendable {
/// stays in use. Any thread; the result comes like any other.
func settleFinishedFades() {
work.begin()
queue.async { [self] in
WorkQueue.async(queue, urgent: true) { [self] in
defer { work.end() }
guard let layout = base, width > 0, layout.width == width else { return }
let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false)
Expand Down Expand Up @@ -565,6 +609,7 @@ final class LayoutEngine: @unchecked Sendable {
}
lock.withLock {
mailbox = nil
laidOut = latestDocument
hiding = TagHiding(fadingFrom: kept)
if kept == nil { fades.removeAll() }
}
Expand Down
Loading
Loading