-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMeasurementCountBenchmark.java
More file actions
311 lines (278 loc) · 14.7 KB
/
Copy pathMeasurementCountBenchmark.java
File metadata and controls
311 lines (278 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package com.demcha.compose;
import com.demcha.compose.document.api.DocumentPageSize;
import com.demcha.compose.document.api.DocumentSession;
import com.demcha.compose.document.backend.fixed.pdf.PdfMeasurementResources;
import com.demcha.compose.document.dsl.PageFlowBuilder;
import com.demcha.compose.document.layout.DocumentGraph;
import com.demcha.compose.document.layout.DocumentLayoutPassContext;
import com.demcha.compose.document.layout.LayoutCanvas;
import com.demcha.compose.document.layout.LayoutCompiler;
import com.demcha.compose.document.layout.LayoutGraph;
import com.demcha.compose.document.layout.NodeRegistry;
import com.demcha.compose.document.node.DocumentNode;
import com.demcha.compose.document.style.DocumentColor;
import com.demcha.compose.document.style.DocumentTextDecoration;
import com.demcha.compose.document.style.DocumentTextStyle;
import java.awt.Color;
import java.lang.management.ManagementFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Deterministic measurement-count and allocation probe for the canonical layout
* pipeline.
*
* <p>For each scenario this harness authors a document through the public DSL,
* then compiles its node graph through a {@link LayoutCompiler} whose
* {@code TextMeasurementSystem} is wrapped in a
* {@link CountingTextMeasurementSystem}. It reports, deterministically and
* independent of wall-clock / GC-timing noise:</p>
*
* <ul>
* <li><b>measurement requests</b> — how the layout asks the measurement
* system for widths (proves F1/F2/F3); and</li>
* <li><b>compile allocation bytes</b> — bytes allocated by the layout
* {@code compile} pass, via
* {@link com.sun.management.ThreadMXBean#getCurrentThreadAllocatedBytes()}.
* Unlike the {@code peakHeapMb} sampled by {@code CurrentSpeedBenchmark}
* (a GC-timing-dependent used-heap delta), allocated-bytes is the
* deterministic memory signal for the allocation findings (F7 style/inset
* churn, F8 box recomputation, fragment re-copy, per-cell table lists).</li>
* </ul>
*
* <p>The allocation window wraps only {@code compile(...)}; font loading and DSL
* authoring happen outside it, so the number reflects layout allocation — the
* thing the optimizations move. Needs no {@code src/main} changes.</p>
*/
public final class MeasurementCountBenchmark {
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final com.sun.management.ThreadMXBean THREAD_MX =
(com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
private static final DocumentTextStyle BODY_STYLE = DocumentTextStyle.builder()
.size(9.5)
.decoration(DocumentTextDecoration.DEFAULT)
.color(DocumentColor.of(new Color(58, 69, 84)))
.build();
private static final String LONG_PARAGRAPH =
("GraphCompose lays out structured business documents efficiently across many pages "
+ "while keeping header and footer placement stable. ").repeat(120);
private static final String LONG_TOKEN_PARAGRAPH =
"Prefix text before an unbreakable token " + "x".repeat(600)
+ " and several trailing words that must still wrap onto the following lines here.";
// High-glyph-diversity accented-Latin (Latin-1) passage: many distinct
// diacritic glyphs and varied words, unlike the single repeated ASCII
// sentence above, so distinctWidthRequests / repeat-rate reflect a non-ASCII,
// high-diversity workload. Standard-14 Helvetica covers Latin-1; true
// CJK / Cyrillic would need an embedded font and is out of scope here.
private static final String ACCENTED_LATIN_PARAGRAPH =
("Le café à Genève - résumé naïve, façon piñata. Über die Größe schön: "
+ "coração São, mañana señor. Déjà brûlée crème, fjörð Århus Tromsø "
+ "Köln Zürich Besançon, garçon élève hôtel. ").repeat(40);
public static void main(String[] args) throws Exception {
BenchmarkSupport.configureQuietLogging();
new MeasurementCountBenchmark().run();
}
private void run() throws Exception {
enableAllocationMeasurement();
System.out.println("GraphCompose Measurement-Count + Allocation Probe");
System.out.println("Timestamp: " + LocalDateTime.now().format(TIMESTAMP_FORMAT));
System.out.println("Thread allocation measurement: " + (allocationSupported() ? "enabled" : "UNAVAILABLE (Alloc KB = n/a)"));
System.out.println();
Map<String, Consumer<PageFlowBuilder>> scenarios = scenarios();
// Warm up the JVM (class loading + JIT) BEFORE the allocation window so the
// "Alloc KB" column reflects steady-state per-document layout allocation, not
// one-time cold-start cost. Without this the FIRST scenario measured carried
// ~36 MB of class-load / JIT / static-init allocation — a JVM artifact, not a
// layout cost (verified: cold first compile 36.6 MB vs warm 0.65 MB for the
// same long-text document). The measurement-COUNT columns are exact either way.
for (int warmup = 0; warmup < 5; warmup++) {
for (Consumer<PageFlowBuilder> author : scenarios.values()) {
measureScenario("warmup", author);
}
}
List<Result> results = new ArrayList<>();
for (Map.Entry<String, Consumer<PageFlowBuilder>> scenario : scenarios.entrySet()) {
results.add(measureScenario(scenario.getKey(), scenario.getValue()));
}
System.out.printf("%-14s | %11s | %9s | %9s | %11s | %8s | %11s | %10s | %6s%n",
"Scenario", "WidthReqs", "Distinct", "Repeat %", "Sum chars", "Max arg", "LineMetrics", "Alloc KB", "Pages");
System.out.println("-".repeat(108));
for (Result result : results) {
CountingTextMeasurementSystem.Counts c = result.counts();
System.out.printf("%-14s | %11d | %9d | %8.1f%% | %11d | %8d | %11d | %10s | %6d%n",
result.scenario(),
c.widthRequests(),
c.distinctWidthRequests(),
c.repeatRatePct(),
c.summedRequestChars(),
c.maxRequestChars(),
c.lineMetricsCalls(),
formatAllocKb(result.compileAllocBytes()),
result.pages());
}
writeReport(results);
}
/**
* The probe's scenarios, in report order. Single source for the probe and for
* {@code MeasurementCountGateTest}, so a scenario added here cannot slip past
* the gate unnoticed.
*
* @return scenario name to document author
*/
static Map<String, Consumer<PageFlowBuilder>> scenarios() {
Map<String, Consumer<PageFlowBuilder>> scenarios = new LinkedHashMap<>();
scenarios.put("long-text", flow ->
flow.addParagraph(p -> p.text(LONG_PARAGRAPH).textStyle(BODY_STYLE)));
scenarios.put("long-token", flow ->
flow.addParagraph(p -> p.text(LONG_TOKEN_PARAGRAPH).textStyle(BODY_STYLE)));
scenarios.put("accented-latin", flow ->
flow.addParagraph(p -> p.text(ACCENTED_LATIN_PARAGRAPH).textStyle(BODY_STYLE)));
scenarios.put("large-table", MeasurementCountBenchmark::authorLargeTable);
return scenarios;
}
/**
* Compiles one scenario and returns its exact measurement counts.
*
* <p>Package-private and static so the gate test can drive the real layout
* pass rather than re-implementing the instrumentation.</p>
*
* @param scenario report label
* @param author document author for the scenario
* @return the scenario's counts, page/fragment totals and compile allocation
* @throws Exception when composition or measurement fails
*/
static Result measureScenario(String scenario, Consumer<PageFlowBuilder> author) throws Exception {
try (DocumentSession session = GraphCompose.document()
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
session.pageFlow(author);
List<DocumentNode> roots = session.roots();
LayoutCanvas canvas = session.canvas();
NodeRegistry registry = session.registry();
try (PdfMeasurementResources resources = PdfMeasurementResources.open(List.of())) {
CountingTextMeasurementSystem counter =
new CountingTextMeasurementSystem(resources.textMeasurementSystem());
DocumentLayoutPassContext context = new DocumentLayoutPassContext(
registry, canvas, resources.fontLibrary(), counter, false);
LayoutCompiler compiler = new LayoutCompiler(registry);
DocumentGraph graph = new DocumentGraph(roots);
// Measure allocation around the layout compile only — font
// loading and authoring are already done, so this is the
// layout pass's own allocation footprint.
long allocBefore = currentThreadAllocatedBytes();
LayoutGraph layout = compiler.compile(graph, context, context);
long allocBytes = allocBefore < 0 ? -1 : currentThreadAllocatedBytes() - allocBefore;
return new Result(scenario, counter.snapshot(), layout.totalPages(), layout.fragments().size(), allocBytes);
}
}
}
private static void authorLargeTable(PageFlowBuilder flow) {
flow.addTable(table -> {
table.autoColumns(6).header("Item", "Qty", "Unit", "Price", "Tax", "Total");
for (int row = 1; row <= 200; row++) {
table.row("Line item " + row, "3", "ea", "12.50", "1.25", "38.75");
}
});
}
private static void enableAllocationMeasurement() {
try {
if (THREAD_MX.isThreadAllocatedMemorySupported() && !THREAD_MX.isThreadAllocatedMemoryEnabled()) {
THREAD_MX.setThreadAllocatedMemoryEnabled(true);
}
} catch (UnsupportedOperationException ignored) {
// Allocation measurement unsupported on this JVM; Alloc KB reports n/a.
}
}
private static boolean allocationSupported() {
try {
return THREAD_MX.isThreadAllocatedMemorySupported() && THREAD_MX.isThreadAllocatedMemoryEnabled();
} catch (UnsupportedOperationException ex) {
return false;
}
}
private static long currentThreadAllocatedBytes() {
if (!allocationSupported()) {
return -1;
}
return THREAD_MX.getCurrentThreadAllocatedBytes();
}
private static String formatAllocKb(long bytes) {
return bytes < 0 ? "n/a" : "%.1f".formatted(bytes / 1024.0);
}
private void writeReport(List<Result> results) throws Exception {
CounterReport report = new CounterReport(
LocalDateTime.now().format(TIMESTAMP_FORMAT),
results.stream().map(Result::toScenarioCounts).toList());
BenchmarkReportWriter.BenchmarkArtifacts artifacts = BenchmarkReportWriter.prepare("counters");
var jsonPath = artifacts.writeJson(report);
var csvPath = artifacts.writeCsv(
"counters",
List.of("scenario", "width_requests", "distinct_width_requests", "repeat_rate_pct",
"summed_request_chars", "max_request_chars", "text_width_calls", "measure_calls",
"line_metrics_calls", "compile_alloc_bytes", "pages", "fragments"),
results.stream()
.map(result -> {
CountingTextMeasurementSystem.Counts c = result.counts();
return List.of(
result.scenario(),
Long.toString(c.widthRequests()),
Long.toString(c.distinctWidthRequests()),
"%.2f".formatted(c.repeatRatePct()),
Long.toString(c.summedRequestChars()),
Long.toString(c.maxRequestChars()),
Long.toString(c.textWidthCalls()),
Long.toString(c.measureCalls()),
Long.toString(c.lineMetricsCalls()),
Long.toString(result.compileAllocBytes()),
Integer.toString(result.pages()),
Integer.toString(result.fragments()));
})
.toList());
System.out.println();
System.out.println("Saved JSON counter report to " + jsonPath);
System.out.println("Saved CSV counter report to " + csvPath);
}
record Result(String scenario,
CountingTextMeasurementSystem.Counts counts,
int pages,
int fragments,
long compileAllocBytes) {
ScenarioCounts toScenarioCounts() {
return new ScenarioCounts(
scenario,
counts.widthRequests(),
counts.distinctWidthRequests(),
counts.repeatRatePct(),
counts.summedRequestChars(),
counts.maxRequestChars(),
counts.textWidthCalls(),
counts.measureCalls(),
counts.lineMetricsCalls(),
counts.lineHeightCalls(),
compileAllocBytes,
pages,
fragments);
}
}
private record ScenarioCounts(String scenario,
long widthRequests,
long distinctWidthRequests,
double repeatRatePct,
long summedRequestChars,
long maxRequestChars,
long textWidthCalls,
long measureCalls,
long lineMetricsCalls,
long lineHeightCalls,
long compileAllocBytes,
int pages,
int fragments) {
}
private record CounterReport(String timestamp, List<ScenarioCounts> scenarios) {
}
}