dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / tools / scroll_bench / bench.lucb
#==============================================================================================
#
# bench - one page: load it, scroll it frame by frame, time the frames
#
# DESCRIPTION:
# The loop of a frame: the wheel event, then the engine's turns until the view presents
# a new frame, then the frame's way to the GPU (see the module's header). Only the time
# spent inside the engine's turns and the frame's delivery counts; sleeping until the
# engine's next deadline does not. A wheel that does not scroll (the page's end) yields no
# frame: after 20 seconds the direction turns (and the run ends when neither way scrolls).
#
# Copyright (c) 2026 the luce-browser authors.
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
## How long to wait for a load or a first frame, and how long without a frame means the page
## did not scroll (long enough for the CPU player's slowest frames), in nanoseconds.
let bench_load_wait: u64 = 60000000000
let bench_no_frame: u64 = 20000000000
## How long a loaded page settles (late images and fonts) before scrolling, in nanoseconds.
let bench_settle: u64 = 1500000000
## The webview behind a webview_api handle.
func bench_web_view(view: webview_api.View) -> webview.WebView*:
return (webview.WebView*)(void*)view
## One engine turn, timed: the nanoseconds it worked. When it had nothing due, the loop sleeps
## (uncounted) until it does, at most a millisecond.
func bench_turn() -> u64:
let start = time.now()
_ = webview_api.process_events()
let worked = time.now() - start
let due = webview_api.next_due()
if due < 0.0 or due > 0.001:
thread.sleep(1)
return worked
## Takes the view's events; answers whether a load other than about:blank finished.
func bench_take_events(view: webview_api.View) -> bool:
var loaded = false
while true:
match webview_api.take_event(view):
.none_: return loaded
.load_finished:
let url = webview_api.finished_load_url(view)
if url.length > 0 and url != "about:blank":
loaded = true
_: _ = 0
## The frames of one run and what they cost.
struct BenchRun:
var times: ak.Vector[u64]
var scrolled: f64
var load: u64
var mismatches: usize
var checks: usize
## Loads `page` into a new view, scrolls it and prints its line.
func bench_page(page: str, options: const Options*):
let view = webview_api.open(options.width, options.height, options.scale)
defer webview_api.close(view)
# The GPU player draws the page from its first frame, as in the application.
if options.player != Player.cpu:
let allocator: memory.Allocator = webview.webview_heap()
with allocator:
webview.webview_set_gpu_player(bench_web_view(view), true)
var run = BenchRun()
if not webview_api.load(view, page):
print(f"{page}: not a location")
return
let start = time.now()
while not bench_take_events(view):
run.load += bench_turn()
if time.now() - start > bench_load_wait:
print(f"{page}: the load did not finish")
return
while webview_api.frame_serial(view) == 0:
run.load += bench_turn()
_ = bench_take_events(view)
if time.now() - start > bench_load_wait:
print(f"{page}: no frame")
return
let settle_end = time.now() + bench_settle
while time.now() < settle_end:
_ = bench_turn()
_ = bench_take_events(view)
var presenter = bench_presenter_open(view, options)
defer bench_presenter_close(&presenter)
# The first frame's delivery is the page's start-up, not a scroll frame.
bench_present(&presenter, view, &run, true)
var direction = 1.0
var misses = 0
var frame: usize = 0
let x = options.width / 2.0
let y = options.height / 2.0
while frame < options.frames:
let before = webview_api.frame_serial(view)
webview_api.wheel(view, x, y, 0.0, direction * options.step, 0)
var worked: u64 = 0
let waited = time.now()
var presented = true
while webview_api.frame_serial(view) == before:
worked += bench_turn()
_ = bench_take_events(view)
if time.now() - waited > bench_no_frame:
presented = false
break
if not presented:
# The page's end: turn around, unless it scrolls neither way.
direction = -direction
misses += 1
if run.scrolled == 0.0 or misses > 2:
break
continue
misses = 0
let delivery = time.now()
bench_present(&presenter, view, &run, frame % 16 == 0)
worked += time.now() - delivery
ak.vector_append_t(&run.times, worked)
run.scrolled += options.step
frame += 1
bench_collect_gpu_time(&presenter)
bench_write_pngs(&presenter, view, page, options)
bench_report(page, &run, &presenter)
bench_presenter_report(&presenter)
if options.layers:
webview.webview_gpu_describe_layers(bench_web_view(view))
if options.census:
bench_print_census(&presenter)
## The names of the blob tags (web.MemoryTag), in order.
let bench_tag_names: str[7] = ["untagged", "parse", "style", "layout", "paint", "image", "gpu_player"]
## Prints the process's memory and a census of the heap after a collection: readable lines,
## then `census key=value ...` and `census_tags key=value ...` lines of bytes for scripts
## (tests/memory).
func bench_print_census(presenter: const BenchPresenter*):
let heap = webview.webview_heap()
let before = webview.webview_memory_census(heap)
let collect_start = time.now()
gc.heap_collect_garbage(heap)
let collect_time = time.now() - collect_start
let census = webview.webview_memory_census(heap)
let process = webview.webview_process_memory()
# The GPU memory the process holds (Metal's currentAllocatedSize; Vulkan's heap usage).
var gpu_used: u64 = 0
if let device = presenter.device:
let device_memory: gpu.DeviceMemory? = device.memory() catch failure:
recover none
if let reported = device_memory:
gpu_used = reported.used
print(f" process: resident {mebibytes(process.resident)} MiB, footprint {mebibytes(process.footprint)} MiB, peak resident {mebibytes(process.peak_resident)} MiB; GPU allocated {mebibytes(gpu_used)} MiB")
print(f" heap: blocks {mebibytes((u64)census.block_bytes)} MiB (free cells {mebibytes((u64)census.free_cell_bytes)}), cached blocks {mebibytes((u64)census.cached_block_bytes)} MiB, large objects {decimal((u64)census.large_objects)} mapping {mebibytes((u64)census.large_object_bytes)} MiB; collection {milliseconds(collect_time)} ms freed {mebibytes((u64)(before.block_bytes + before.large_object_bytes - census.block_bytes - census.large_object_bytes))} MiB")
print(f" live: cells {mebibytes((u64)census.cell_bytes)} MiB, blobs {mebibytes((u64)census.blob_bytes)} MiB, atomic blobs {mebibytes((u64)census.atomic_blob_bytes)} MiB")
var tags = owned(f" live blobs by tag (before collecting):")
for tag in 0..<bench_tag_names.length:
tags = owned(f"{tags} {bench_tag_names[tag]} {mebibytes((u64)census.blob_bytes_by_tag[tag])} ({mebibytes((u64)before.blob_bytes_by_tag[tag])})")
print(tags)
let kinds = census.cell_bytes_by_kind
print(f" cells by kind: dom {mebibytes((u64)kinds[0])}, style {mebibytes((u64)kinds[1])}, layout {mebibytes((u64)kinds[2])}, paint {mebibytes((u64)kinds[3])}, other {mebibytes((u64)kinds[4])} MiB")
for index in 0..<(census.class_count if census.class_count < 8 else 8):
let entry = &census.classes[index]
print(f" {bench_pad(webview.webview_memory_class_name(entry), 40)} {bench_pad(decimal((u64)entry.cells), 9)} {mebibytes((u64)entry.bytes)} MiB")
var line = owned(f"census available={decimal(1 if process.available else 0)} peak_resident={decimal(process.peak_resident)} resident={decimal(process.resident)} footprint={decimal(process.footprint)} gpu_allocated={decimal(gpu_used)}")
line = owned(f"{line} heap_blocks={decimal((u64)census.block_bytes)} large_objects={decimal((u64)census.large_object_bytes)} cached_blocks={decimal((u64)census.cached_block_bytes)}")
line = owned(f"{line} cells={decimal((u64)census.cell_bytes)} blobs={decimal((u64)census.blob_bytes)} atomic_blobs={decimal((u64)census.atomic_blob_bytes)}")
print(line)
# The live blobs by tag, on a line of their own (owned() keeps at most 512 bytes).
var tag_line = "census_tags"
for tag in 0..<bench_tag_names.length:
tag_line = owned(f"{tag_line} {bench_tag_names[tag]}={decimal((u64)census.blob_bytes_by_tag[tag])}")
print(tag_line)
## The average and 95th percentile of `times` (ns).
func bench_statistics(times: const ak.Vector[u64]*) -> u64[2]:
let count = ak.vector_size(times)
var sorted = ak.Vector[u64]()
defer ak.vector_clear(&sorted)
var total: u64 = 0
for value in ak.vector_span_const(times):
total += value
ak.vector_append_t(&sorted, value)
let values = ak.vector_span(&sorted)
# Insertion sort: a few hundred frames.
for i in 1..<values.length:
let value = values[i]
var j = i
while j > 0 and values[j - 1] > value:
values[j] = values[j - 1]
j -= 1
values[j] = value
let average: u64 = total // (u64)count if count > 0 else 0
let p95: u64 = values[(count * 95) // 100 if (count * 95) // 100 < count else count - 1] if count > 0 else 0
return [average, p95]
## Prints a page's line: CPU frame time (the main thread's), then the GPU's (the GPU player).
func bench_report(page: str, run: const BenchRun*, presenter: const BenchPresenter*):
let cpu = bench_statistics(&run.times)
let name = bench_short_name(page)
let check = owned(f"{decimal((u64)run.mismatches)}/{decimal((u64)run.checks)} differ") if run.checks > 0 else "-"
var gpu_column: str = "-"
if ak.vector_size(&presenter.gpu_times) > 0:
let gpu_time = bench_statistics(&presenter.gpu_times)
gpu_column = owned(f"{milliseconds(gpu_time[0])}/{milliseconds(gpu_time[1])}")
if presenter.untimed > 0:
gpu_column = owned(f"{gpu_column} ({decimal(presenter.untimed)} untimed)")
print(f"{bench_pad(name, 24)} {bench_pad(milliseconds(run.load), 8)} {bench_pad(milliseconds(cpu[0]), 13)} {bench_pad(milliseconds(cpu[1]), 13)} {bench_pad(gpu_column, 15)} {bench_pad(decimal((u64)run.scrolled), 12)} {bench_pad(bench_presenter_tiles(presenter), 10)} {bench_pad(mebibytes(peak_resident()), 9)} {check}")
## The last path component of `page` (its directory for an index.html).
func bench_short_name(page: str) -> str:
var name = page
if strings.ends_with(name, "/index.html"):
name = (str)name.bytes[..<name.length - 11]
if let slash = strings.find_last(name, "/"):
name = (str)name.bytes[slash + 1..]
return name
## `text` padded with spaces to `width`.
func bench_pad(text: str, width: usize) -> str:
if text.length >= width:
return text
var padded = strings.copy(text) catch failure: trap("out of memory")
for _ in 0..<width - text.length:
padded = strings.join([padded, " "], "") catch failure: trap("out of memory")
return padded
## Writes the last frame of each player as PREFIX-NAME-PLAYER.png.
func bench_write_pngs(presenter: BenchPresenter*, view: webview_api.View, page: str, options: const Options*):
let prefix = options.png_prefix else return
let width = (usize)webview_api.frame_width(view)
let height = (usize)webview_api.frame_height(view)
let name = bench_short_name(page)
if presenter.cpu_pixels.length > 0:
bench_write_png(presenter.cpu_pixels, width, height, owned(f"{prefix}-{name}-cpu.png"))
if presenter.gpu_pixels.length > 0:
bench_write_png(presenter.gpu_pixels, width, height, owned(f"{prefix}-{name}-gpu.png"))
## Writes straight RGBA `pixels` as a PNG at `path`.
func bench_write_png(pixels: const u8[], width: usize, height: usize, path: str):
var encoded = Buffer()
defer encoded.close()
png.encode_rgba8(pixels, width, height, &encoded, png.EncodeOptions(threads = 1)) catch failure:
print(f"scroll_bench: {path}: {failure.message}")
return
let name = (c.str)(strings.copy(path) catch failure: trap("out of memory"))
files.write(name, encoded.view()) catch failure: print(f"scroll_bench: {path}: {failure.message}")