Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Measuring

A trace line per frame, a resize run that reports what it cost, benchmarks that are never a gate, and the flags that change what you measure.

By the end of this chapter you can read where a slow frame went, run the showcase under load and get one line that says what it cost, run every benchmark in the repository, and tell a benchmark’s number from a frame’s.

Per-frame timings at TRACE

Every frame logs its stages at trace. The showcase reads the level from one property, and an application of your own sets the dev.goldberry logger to trace in its SLF4J binding. The logging chapter has the configuration.

./gradlew run -Dgoldberry.log.level=TRACE

The window’s line splits the frame into the buffer, the paint and the present, and paint into three parts, because the split says where a frame’s time goes:

frame <size> in <total>us: buffer <n>, paint <n> (begin <n>, draw <n>, end <n>), present <n>

begin attaches the context, draw is the painter’s own work, and end waits for the paint workers. During a resize this line is the difference between “the toolkit is slow” and “the platform is”.

The launcher adds a second line per frame that did something, split by the stages of the widget pipeline. It is a system property rather than a log level, because a diagnostic that cost an isTraceEnabled() per element per frame would be measuring itself:

./gradlew run -Dgoldberry.trace.frames=true    # frames that did something
./gradlew run -Dgoldberry.trace.frames=all     # and the quiet ones

A frame whose cascade is slow per element reads:

frame 268 | build 0.010 style 8.636 layout 1.115 raster 1.304 ms
  | elements 125, built 0, resolved 3, invalidated 1
  | cascade 5.133 identity 0.956 motion 0.176 boxes 1.467
  | text 17 cached, 6 shaped | damage 3

The counts beside the timings are the point. resolved 3 beside style 8.636 is a cascade that is slow per element rather than one running too often. A frame that is slow for a reason the timings cannot show is explained by a count and not a duration: a style cache missing on every element, or a click invalidating the whole tree, shows in the counts first.

Tip

The showcase has a HUD on Ctrl+F that shows the same stages over the last sixty frames. Switch it on during a drag or a resize, when there is something to watch.

The showcase under load

The launcher accepts these flags and leaves every other argument to the application:

FlagWhat it does
--frames=NPaints N frames and exits
--size=WxHOpens the window at that size
--resize=WxHWalks the window a pixel a frame on each axis from its opening size to WxH and back, for as long as the run lasts
--late-budget=NPast N missed refreshes the launcher exits non-zero after shutdown, with the summary in the message

A drag is a resize event per pointer motion, and that is the load a frame loop has to be measured under. A jump from one size to another is one reallocation and says nothing. The walk steps between frames, because a resize asked for from inside a painter changes the size under the frame being painted on every driver where a window resize is synchronous.

./example/build/native/goldberry-showcase-linux-x64 --frames=300 --resize=1580x1100

After the window closes the launcher logs one line, in Locale.ROOT so a script can grep it:

frames: 300 frame(s) painted, 2 late; paint mean 1.31 ms, worst 8.90 ms; display 60.0 Hz

A display that reports no refresh rate shows as display 0.0 Hz, and “late” then counts missed ticks of the pacer’s own timer. --late-budget is for a run against a real display, which is where it means something.

Under Gradle the same run is ./gradlew run -Pgoldberry.example.frames=300, and -Pgoldberry.backend.videoDriver=dummy keeps it off the real compositor. Use the Gradle property rather than an environment variable, because a JavaExec fork inherits the daemon’s environment and not the shell’s.

./goldberry-showcase-macos-aarch64 -Dgoldberry.startup.log.level=TRACE --frames=1

The timeline measures from process start to the first successful presentation. The macOS Showcase workflow includes it in the job summary.

Every frame, and the hitch

host.window().onFrame(frame -> …) hears every frame the window presents, with its interval, its paint and stages, the refreshes it was late by, and on a composited window its upload, acquire, submit and GPU layers. The listener is handed the same object every frame, so listening costs nothing; keep one with frame.copy().

window.onFrame(frame -> {
    if (frame.intervalNanos() > 25_000_000) {
        hitches.add(frame.copy());
    }
});

frames.percentile(FrameStage.INTERVAL, 99) is the hitch a mean smooths away, over the last sixty frames; percentile(FrameStage.PAINT, 50) is the median paint. frames.layers() is what the GPU layers took to render again, a canvas3d’s renderer recording its passes, apart from the compositor’s own work.

The benchmark lane

A benchmark is a JUnit class under a module’s src/benchmark/java, and a probe is a main beside it. ./gradlew benchmark runs every module’s benchmarks, ./gradlew :widgets:benchmark one module’s, and check only compiles them, so a benchmark that stops building fails on the commit that broke it. They print their measurements and assert almost nothing, because a timing assertion on a shared machine fails for reasons that have nothing to do with the code.

They run one module at a time, whatever org.gradle.parallel says: every benchmark task holds a shared build service with one slot. Two benchmarks measured together measure each other, and a table taken beside a compiler is a table of the compiler.

The inventory:

BenchmarkModuleWhat it prices
PaintBenchmark:corePainting a frame, and what the paint workers do to it
TextBenchmark:coreThe text path: shaping, the paragraph cache, wrapping
EditorKeystrokeBenchmark:coreOne keystroke into a 2 kB, a 50 kB and a 500 kB editor document
FrameBenchmark:widgetsA frame of a real widget tree, split by stage
DeepTreeStyleBenchmark:widgetsA 50-, 100- and 200-deep tree’s first frame and a middle ancestor’s hover, against the catalog’s sheets
TextAreaFrameBenchmark:widgetsOne keystroke into a 2 kB, a 50 kB and a 500 kB note
AxisLabellingBenchmark:widgetsOne numeric and one time-axis labelling, against a third of a frame
MarkdownFrameBenchmark:htmlThe same keystroke through a markdown-view, with the Markdown parser timed alone as a control row
PlaneCopyBenchmark:mediaCopying and converting a 4K picture’s planes, against a picture’s time at 60 fps
ReadPacketBenchmark:mediaOne read_packet through the upcall stub against a direct call
BindingSchemeBenchmark:weaverThe two ways of binding a model, against each other
BindingCodegenBenchmark:weaverWhether a jar should generate its binding rather than reflect
DowncallBenchmark:nativesOne foreign call, held both ways
ModifierPollBenchmark:nativesThe per-event modifier poll
BindingBenchmark:exampleA Property per value against plain bound fields, and the showcase’s own names
FrameBudgetBenchmark:exampleA frame of the real application, stage by stage and resolution by resolution

And the probes, each run by a task of its own and read by a person, because they open a real window or device and the numbers are the machine’s:

ProbeTaskWhat it measures
GpuPresentProbe:natives:gpuPresentProbeWindow-surface and composited present, and the swapchain switch
GpuVideoProbe:gpu:gpuVideoProbeA composited frame with a 4K video layer under the UI
VideoLayerProbe:gpu:videoLayerProbeThe video layer’s upload of a new 4K picture each frame
VideoPresentProbe:media:videoPresentProbeA minute of 4K60 video in a window: dropped pictures and CPU time

Run one by name:

./gradlew :widgets:benchmark --tests '*TextAreaFrameBenchmark*'
./gradlew :example:benchmark --tests '*FrameBudgetBenchmark*' -i
./gradlew benchmark --tests '*Text*'

The last names benchmarks in two modules, and every other module’s task is given the same filter and finds nothing, which is not a failure.

MarkdownFrameBenchmark carries a control row, the Markdown parser timed on its own. Two runs whose parse times disagree are two runs on two differently loaded machines, and their other rows should not be compared.

JMH on :core

The hot seams that are pure logic have JMH, as a src/jmh source set with forks, warm-up and a blackhole, so a number is not the JIT specialising a loop away. CascadeBenchmark resolves one element against a six-rule sheet at 0.476 ± 0.067 µs/op.

./gradlew :core:jmh

That is what JMH adds over the benchmark task, and the only reason to run both.

A cost is guarded by a count, never by a clock

A test under check that asserts a millisecond fails for what else the machine was doing. FrameBudgetBenchmark’s style row reads 3.6 ms on an idle machine and 20 ms under a parallel Gradle, on the same commit, which is why it is a benchmark and its table is read rather than asserted.

What check is owed instead is a count. A keystroke into a 500 kB note shapes and draws about what a keystroke into a 2 kB note does, 2 021 characters against 1 941, and a test under check asserts that count rather than a time. A markdown-view is held the same way, in blocks built, blocks kept and paragraphs shaped. A count says the same thing under a parallel build and a millisecond does not.

Important

A benchmark’s scaffolding is under check. The two names BindingBenchmark resolves are also resolved by a test on every build.

The flags

Each is a system property on the Java command line, so -D on a plain launch, and on ./gradlew run the showcase forwards the ones below.

PropertyValuesWhat it changesDefault
goldberry.paint.threads0 for synchronous painting, N to pin the worker countThe paint workersup to four on any surface over 400×300
goldberry.frame.rateN overrides the display’s rate, 0 measures the unthrottled loopThe pacer, which 0 switches offthe rate read off the window’s display
goldberry.backend.vsyncfalseStops asking the windowing layer to hold each present until vertical blanktrue
goldberry.gpuoffKeeps every window on the CPUon, when goldberry-gpu is on the module path
goldberry.gpu.compositealways, auto, neverWhether a window is composited always, only while it shows GPU content, or not at allalways
goldberry.backend.videoDriverdummyThe windowing layer’s video driver, for a headless run that touches no compositorthe windowing layer’s own choice, X11 first on Linux
goldberry.trace.framestrue, allThe launcher’s per-frame stage line, with its countsoff
goldberry.log.nativefalseGives the native libraries their stderr back, past the SLF4J bridgetrue, the bridge installed
goldberry.log.levelTRACEThe showcase’s logback.xml level for dev.goldberry. Your application names its ownDEBUG

A tuning flag that is not understood is taken as the default. A typo should not stop a window opening.

Showcase argumentEffect
--capture=PATHWrites the last frame of a bounded run as a PNG
--capture-at=Nwrites frame N to the --capture= file and keeps running
--verify-native-librariesExercises the packaged native libraries and exits

A benchmark is not a frame

The same 960×640 scene paints in 0.34 ms in PaintBenchmark and in 2.15 ms in the running showcase, both with four workers. The difference is present. The benchmark’s own loop, run inside the live application between two real frames, is four times faster than the frames on either side, and with present skipped and nothing else changed the paint falls from 2.193 ms to 0.574 ms.

present moves megabytes and crosses into the kernel, and by the time the next frame begins the pipelines, the destination pixels, the glyph caches and the page tables that reach them have all been displaced. So:

  • A benchmark compares options against each other. Worker counts, surface sizes and algorithms, with everything else held constant.
  • A claim about what a frame costs comes from a frame. Read it off the trace line or the launcher’s summary, in a window that presents.

The summary page quotes both numbers for that reason, and labels each.