SPB Git

Repository Public

main.swift 7.1 KB 134 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/orixbench/main.swift3// Description: Engine benchmarks on a generated long document. Prints measured times as JSON; nothing is estimated.4//              Usage: swift run -c release orixbench [chapters] [output.json]   (40 chapters ≈ 490 pages)5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer11import DocLayout12import DocReferences13import DocAutomation1415func time<T>(_ body: () throws -> T) rethrows -> (T, Double) {16    let start = DispatchTime.now().uptimeNanoseconds17    let r = try body()18    return (r, Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000)19}2021let sentence = "The committee reviewed the proposal in detail and concluded that the schedule remained realistic, provided the remaining dependencies were resolved before the end of the quarter. "2223/// A report-like document: chapters, sections, body text, tables, footnotes, equations, a contents block and running headers.24func makeDocument(chapters: Int) -> DocumentModel {25    var doc = DocumentModel(styles: .standard(theme: .academic), pageSetup: PageSetup(paper: .letter))26    for l in 1...3 { var s = doc.styles.style(StyleID.heading(l))!; s.numbered = true; doc.styles.upsert(s) }27    doc.meta.title = "Benchmark document"28    doc.pageSetup.header.default = [Paragraph(style: StyleID.header, runs: [Run(inline: .field(.headingText(level: 1))), Run("\t\t"), Run(inline: .field(.title))])]29    doc.pageSetup.footer.default = [Paragraph(style: StyleID.footer, runs: [Run("\t"), Run(inline: .field(.pageNumber)), Run(" / "), Run(inline: .field(.pageCount))])]30    var body: [Block] = [.paragraph(Paragraph("Benchmark document", style: StyleID.title)), .toc(TOCBlock()), .pageBreak(BreakBlock())]31    var n = 032    for c in 1...chapters {33        body.append(.paragraph(Paragraph("Chapter \(c) of the benchmark", style: StyleID.heading(1), props: ParaProps(pageBreakBefore: c > 1))))34        for s in 1...4 {35            body.append(.paragraph(Paragraph("Section \(c).\(s)", style: StyleID.heading(2))))36            for p in 1...9 {37                n += 138                var runs = [Run(String(repeating: sentence, count: 3 + (n % 4)))]39                if p % 4 == 0 {40                    let note = Note(kind: .footnote, paragraphs: [Paragraph("Note \(n): supporting detail for the statement above.", style: StyleID.footnoteText)])41                    doc.notes[note.id] = note42                    runs.append(Run(inline: .note(NoteRef(kind: .footnote, id: note.id))))43                }44                if p % 5 == 0 { runs.append(Run(" Emphasis is used sparingly.", props: CharProps(italic: true))) }45                body.append(.paragraph(Paragraph(runs: runs)))46            }47            if s % 2 == 0 {48                body.append(.table(Table(strings: [["Item", "Q1", "Q2", "Q3", "Q4"]] + (1...8).map { r in ["Line \(r)"] + (1...4).map { "\(r * $0 * 137 % 1000)" } }, width: 468)))49                body.append(.paragraph(Paragraph(style: StyleID.caption, runs: [Run("Table\u{00A0}"), Run(inline: .field(.sequence("Table"))), Run(". Quarterly values for section \(c).\(s).")])))50            } else {51                body.append(.paragraph(Paragraph(props: ParaProps(alignment: .center), runs: [Run(inline: .equation(Equation(latex: "\\sigma_{\(s)}^2 = \\frac{1}{n}\\sum_{i=1}^{n}(x_i - \\bar{x})^2", display: true)))])))52            }53        }54    }55    body.append(.paragraph(Paragraph()))56    doc.body = body57    return doc58}5960let chapters = CommandLine.arguments.count > 1 ? Int(CommandLine.arguments[1]) ?? 40 : 4061var results: [String: Any] = [:]62var doc = makeDocument(chapters: chapters)63let stats = DocumentStatistics(doc)64let engine = CitationEngine(document: doc)65let cache = LayoutCache()6667let (layout, tLayout) = time { Paginator.layout(doc, citations: engine, cache: cache) }68results["document"] = ["chapters": chapters, "blocks": doc.body.count, "words": stats.words, "pages": layout.pageCount, "tables": stats.tables, "footnotes": doc.notes.count, "equations": stats.equations]69results["layout_cold_ms"] = tLayout70results["layout_passes"] = layout.passes7172// Typing: one character inserted in a paragraph in the middle of the document, then a full relayout, 200 times.73var editor = DocumentEditor(doc: doc)74let mid = doc.body.indices.filter { doc.body[$0].paragraph?.style == StyleID.normal && (doc.body[$0].paragraph?.length ?? 0) > 100 }75let target = mid[mid.count / 2]76editor.selection = Selection(caret: Position(block: target, offset: 40))77var previous = layout78var samples: [Double] = []79var editSamples: [Double] = []80for i in 0..<200 {81    let (_, te) = time { editor.insertText(i % 7 == 6 ? " " : "a") }82    let (l, tl) = time { Paginator.layout(editor.doc, citations: engine, cache: cache, previous: previous) }83    previous = l84    samples.append(tl); editSamples.append(te)85}86samples.sort(); editSamples.sort()87results["keystroke_relayout_ms"] = ["median": samples[100], "p95": samples[190], "max": samples[199]]88results["keystroke_model_edit_ms"] = ["median": editSamples[100], "p95": editSamples[190]]8990// A paragraph break near the start (everything after it moves).91editor.selection = Selection(caret: Position(block: 5, offset: 0))92let (_, tBreak) = time { editor.insertParagraphBreak(); previous = Paginator.layout(editor.doc, citations: engine, cache: cache, previous: previous) }93results["paragraph_break_at_start_relayout_ms"] = tBreak9495let (found, tFind) = time { doc.findAll("schedule") }96results["find_all_ms"] = tFind97results["find_matches"] = found.count98let (_, tNumbering) = time { Numbering(doc) }99results["numbering_ms"] = tNumbering100101let (pdf, tPDF) = time { PDFPublisher.publish(doc, citations: engine) }102results["pdf_export_ms"] = tPDF103results["pdf_bytes"] = pdf.data.count104results["pdf_pages"] = pdf.pageCount105106let (native, tSave) = try time { try DocumentConverter.export(doc, format: .orixdoc) }107results["native_save_ms"] = tSave108results["native_bytes"] = native.data.count109let (_, tOpen) = try time { try DocumentConverter.importDocument(native.data, format: .orixdoc) }110results["native_open_ms"] = tOpen111let (reopened, _) = try time { try DocumentConverter.importDocument(native.data, format: .orixdoc) }112let (_, tOpenLayout) = time { Paginator.layout(reopened.document, citations: engine) }113results["open_and_first_layout_ms"] = tOpen + tOpenLayout114115let (docx, tDocxOut) = try time { try DocumentConverter.export(doc, format: .docx) }116results["docx_export_ms"] = tDocxOut117results["docx_bytes"] = docx.data.count118let (_, tDocxIn) = try time { try DocumentConverter.importDocument(docx.data, format: .docx) }119results["docx_import_ms"] = tDocxIn120121var usage = rusage()122getrusage(RUSAGE_SELF, &usage)123results["peak_memory_mb"] = Double(usage.ru_maxrss) / 1_048_576124results["machine"] = ["cores": ProcessInfo.processInfo.activeProcessorCount, "os": ProcessInfo.processInfo.operatingSystemVersionString]125#if DEBUG126results["build"] = "debug"127#else128results["build"] = "release"129#endif130131let json = try JSONSerialization.data(withJSONObject: results, options: [.prettyPrinted, .sortedKeys])132if CommandLine.arguments.count > 2 { try json.write(to: URL(fileURLWithPath: CommandLine.arguments[2])) }133print(String(decoding: json, as: UTF8.self))134
Files main
Menu

Theme