Merge pull request #5 from ludovic111/process-memory-measurements

Measure resident process memory during game benchmarks
This commit is contained in:
Ludovic Marie
2026-10-03 22:24:21 +02:00
committed by GitHub
16 changed files with 254 additions and 13 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ Client-first performance research for Minecraft Java **26.3**, preserving vanill
## Play on your Mac
Download **horizon-mac-starter-0.5.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
Download **horizon-mac-starter-0.6.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on your 16 GB M2 Pro. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux.
@@ -41,7 +41,7 @@ Press **F8** during gameplay to start a 120-second recording, or again to stop e
Use separate identical world copies and the same camera route, resolution, render/simulation distance, heap, VSync and FPS limit. Warm up, then alternate at least three baseline/optimized runs. Test fresh chunk exploration separately. For everyday play cap FPS or enable VSync to reduce power usage.
The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Heap is **not process RSS or unified GPU memory**.
The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, sampled process RSS when available, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Resident process memory is sampled on a shared background thread only during recordings; it includes native resident pages, while heap measures JVM objects. Neither is a complete measurement of unified GPU memory. [Memory measurement details](docs/process-memory.md).
```sh
python3 tools/compare_benchmarks.py baseline-frames.json optimized-frames.json --strict
+16
View File
@@ -22,6 +22,22 @@ Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initi
## Interpretation limits
The 0.6.0 resident-memory sampler ran in the actual adaptive-pacing demo world.
A 120-second recording produced 370 frame intervals and 2,407 server-tick samples;
both CSV counts and mean durations match their JSON summaries. Each report has
120 successful RSS samples, a peak of about 2,643 MiB, and a last-sample age under
800 ms. The runtime JAR matches the release candidate byte-for-byte. After capture,
the sampler thread waits without further scheduled reads. Native-read tests also
pass on hosted Windows x64, Linux x64 and Apple Silicon macOS 26; unsupported
reader behavior preserves timing samples and omits unavailable RSS fields.
These numbers validate reporting in this particular software-rendered workload,
not a RAM reduction or a prediction of the user's Mac memory use.
The 0.5.0 offline viewer passed Chromium checks using real frame/tick JSON and CSV
files, charts, exports, malformed inputs, kind mismatches, escaped profile labels,
and mobile layout. It is self-contained and has no network dependencies. Its game
runtime classes are identical to 0.4.0, apart from mod version metadata.
The 0.4.0 worker-pacing hook also renders the demo world with the complete mod stack.
Both pacing and adaptive controls are captured as enabled in the final build's
120-second frame report. It produced 359 frame intervals and 2,401 integrated-server
+44
View File
@@ -0,0 +1,44 @@
# Measuring resident process memory
Horizon Lab 0.6.0 records process RSS alongside JVM heap and nonheap pools. RSS
counts resident pages belonging to the Minecraft process, including native
allocations and mapped pages. It helps detect cases where reducing heap use
merely moves memory elsewhere. It is not unique physical-memory ownership or
a complete accounting of GPU allocations, shared pages, compressed memory,
swap, or Apple Silicon unified memory. Do not add heap to RSS: heap pages can
already be included in it.
Minecraft 26.3 already ships OSHI 6.9.0 and JNA on both client and server. The
original mod uses those dependencies without embedding them. Native reader
initialization and refresh happen on a low-priority daemon thread, never on
the render or server-tick thread. One reader serves overlapping frame and
tick recordings. Reads run about once per second only while recordings are
active; the scheduler stops polling when the last recording finishes. Ordinary
gameplay without a benchmark performs no resident-memory reads.
Reports include these optional schema-1 fields:
| Field | Meaning |
| --- | --- |
| `process_rss_peak_sampled_bytes` | Largest successful resident-memory sample during this recording |
| `process_rss_last_sampled_bytes` | Last successful sample, which can precede recording completion |
| `process_rss_samples` | Number of successful samples delivered to this recording |
| `process_rss_sample_interval_ms` | Requested 1,000 ms interval; reads can take longer |
| `process_rss_last_sample_age_ms` | Time from the last successful sample to report completion |
Unsupported or failed reads leave these fields absent if no sample succeeded;
zero is not used as a substitute. Frames and ticks continue recording. A read
that completes after a recording finishes is ignored. Sampled peaks can miss
brief spikes, and the initial read can be delayed by native-library startup.
The offline viewer compares RSS separately from heap/nonheap and warns about
stale resident samples. Keep recording duration, workload and warm-up matched
when comparing peaks. Process CPU counters cover the whole process over the
recording wall time, including native work and the integrated server; they do
not identify which thread or mod caused CPU use.
The native-read test exercises the real library, overlapping recordings,
background execution, idle cancellation and unavailable-reader behavior on
the build platform. This validates measurement availability, not an FPS or
RAM optimization result. Real game integration and platform results are
recorded in the release validation document after they finish.
@@ -4,6 +4,8 @@ import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import dev.horizonlab.metrics.Recording;
import dev.horizonlab.metrics.Reports;
import dev.horizonlab.metrics.ProcessMemoryMonitor;
import dev.horizonlab.metrics.ResidentMemory;
import java.nio.file.Path;
import java.util.Map;
import net.fabricmc.api.ModInitializer;
@@ -20,6 +22,7 @@ public final class HorizonLab implements ModInitializer {
private static volatile Recording ticks;
@Override public void onInitialize() {
ProcessMemoryMonitor.configure(new ResidentMemory());
CommandRegistrationCallback.EVENT.register((dispatcher, context, selection) -> dispatcher.register(
Commands.literal("horizonserver")
.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_ADMIN))
@@ -0,0 +1,53 @@
package dev.horizonlab.metrics;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
/** One background reader for this process, active only while recordings exist. */
public final class ProcessMemoryMonitor {
private static final Set<Recording> ACTIVE = ConcurrentHashMap.newKeySet();
private static final ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "Horizon process memory");
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
return thread;
});
private static volatile LongSupplier reader;
private static ScheduledFuture<?> polling;
private ProcessMemoryMonitor() {}
public static synchronized void configure(LongSupplier residentMemoryReader) {
if (!ACTIVE.isEmpty()) throw new IllegalStateException("Configure before starting recordings");
reader = residentMemoryReader;
}
static synchronized void track(Recording recording) {
if (reader == null) return;
ACTIVE.add(recording);
if (polling == null) polling = EXECUTOR.scheduleWithFixedDelay(ProcessMemoryMonitor::poll, 0, 1, TimeUnit.SECONDS);
}
static synchronized void untrack(Recording recording) {
ACTIVE.remove(recording);
if (ACTIVE.isEmpty() && polling != null) {
polling.cancel(false);
polling = null;
}
}
private static void poll() {
Recording[] recordings = ACTIVE.toArray(Recording[]::new);
if (recordings.length == 0) return;
long bytes;
try { bytes = reader.getAsLong(); }
catch (RuntimeException | LinkageError unavailable) { return; }
if (bytes <= 0) return;
for (Recording recording : recordings) recording.residentMemory(bytes);
}
}
@@ -30,6 +30,11 @@ public final class Recording {
private long peakHeap;
private long peakNonHeap;
private int resourceSamples;
private long residentEnd;
private long residentPeak;
private int residentSamples;
private long residentSampleNs;
private boolean finished;
public Recording(String label, String kind, Path output, int seconds, Map<String, Object> context) {
if (seconds < 1 || seconds > 600) throw new IllegalArgumentException("Duration must be 1..600 seconds");
@@ -44,10 +49,11 @@ public final class Recording {
this.initialGcMs = gcMs();
this.initialCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime();
sampleResources(startedNs);
ProcessMemoryMonitor.track(this);
}
public synchronized void add(long ns) {
if (ns <= 0) return;
if (ns <= 0 || finished) return;
long now = System.nanoTime();
if (now >= nextResourceSampleNs) sampleResources(now);
if (count == samples.length) { dropped++; return; }
@@ -58,6 +64,8 @@ public final class Recording {
public synchronized void players(int players) { peakPlayers = Math.max(players, peakPlayers); }
public synchronized Snapshot finish() {
finished = true;
ProcessMemoryMonitor.untrack(this);
sampleResources(System.nanoTime());
Map<String, Object> metadata = new LinkedHashMap<>(context);
metadata.put("label", label);
@@ -83,6 +91,13 @@ public final class Recording {
metadata.put("nonheap_used_peak_sampled_bytes", peakNonHeap);
metadata.put("resource_samples", resourceSamples);
metadata.put("resource_sample_interval_ms", 1000);
if (residentSamples > 0) {
metadata.put("process_rss_last_sampled_bytes", residentEnd);
metadata.put("process_rss_peak_sampled_bytes", residentPeak);
metadata.put("process_rss_samples", residentSamples);
metadata.put("process_rss_sample_interval_ms", 1000);
metadata.put("process_rss_last_sample_age_ms", (System.nanoTime() - residentSampleNs) / 1e6);
}
long endCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime();
if (initialCpuNs >= 0 && endCpuNs >= initialCpuNs) {
double cpuSeconds = (endCpuNs - initialCpuNs) / 1e9;
@@ -94,6 +109,14 @@ public final class Recording {
return new Snapshot(label, kind, output, Arrays.copyOf(samples, count), metadata);
}
synchronized void residentMemory(long bytes) {
if (finished || bytes <= 0) return;
residentEnd = bytes;
residentPeak = Math.max(residentPeak, bytes);
residentSamples++;
residentSampleNs = System.nanoTime();
}
private void sampleResources(long now) {
peakHeap = Math.max(peakHeap, memory.getHeapMemoryUsage().getUsed());
peakNonHeap = Math.max(peakNonHeap, memory.getNonHeapMemoryUsage().getUsed());
@@ -30,7 +30,7 @@ public final class Reports {
report.put("stats", stats);
report.put("samples_file", csv.getFileName().toString());
report.put("note", snapshot.kind().equals("frames")
? "Frame start intervals include frame limiting and presentation waits; menus, pauses and unfocused frames are excluded. Not GPU timings or process RSS."
? "Frame start intervals include frame limiting and presentation waits; menus, pauses and unfocused frames are excluded. Not GPU timings. Process RSS, when available, is sampled separately."
: "Tick execution durations exclude scheduler sleep. meanRate is execution capacity, not observed TPS.");
Path json = snapshot.output().resolve(name + ".json");
Files.writeString(json, new GsonBuilder().setPrettyPrinting().create().toJson(report) + "\n");
@@ -0,0 +1,20 @@
package dev.horizonlab.metrics;
import java.util.function.LongSupplier;
import oshi.SystemInfo;
import oshi.software.os.OSProcess;
/** Uses Minecraft's existing OSHI dependency; initialization stays on the sampler thread. */
public final class ResidentMemory implements LongSupplier {
private OSProcess process;
private boolean initialized;
@Override public long getAsLong() {
if (!initialized) {
initialized = true;
var os = new SystemInfo().getOperatingSystem();
process = os.getProcess(os.getProcessId());
}
return process != null && process.updateAttributes() ? process.getResidentSetSize() : -1;
}
}
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "horizonlab",
"version": "0.5.0",
"version": "0.6.0",
"name": "Horizon Lab",
"description": "Client frame pacing and server tick measurements for reproducible optimization experiments.",
"authors": [
@@ -32,6 +32,20 @@ public final class MetricsTest {
check((double) snapshot.metadata().get("process_cpu_seconds") >= 0, "CPU time is nonnegative");
}
check(!snapshot.label().contains("/"), "safe report filename");
check(!snapshot.metadata().containsKey("process_rss_peak_sampled_bytes"), "unavailable RSS is absent, not zero");
Recording resident = new Recording("memory", "frames", Path.of("unused"), 10, Map.of());
resident.residentMemory(-1);
resident.residentMemory(100);
resident.residentMemory(200);
resident.residentMemory(150);
resident.add(10_000_000);
var residentSnapshot = resident.finish();
resident.residentMemory(999);
resident.add(10_000_000);
check(residentSnapshot.metadata().get("process_rss_last_sampled_bytes").equals(150L), "last RSS is not called end memory");
check(residentSnapshot.metadata().get("process_rss_peak_sampled_bytes").equals(200L), "RSS peak can exceed last sample");
check(residentSnapshot.metadata().get("process_rss_samples").equals(3), "invalid memory samples excluded");
check(resident.finish().samples().length == 1, "late samples do not change a finished recording");
System.out.println("Metrics tests passed.");
}
@@ -0,0 +1,59 @@
package dev.horizonlab.metrics;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/** Real native reads on each CI platform; also checks idle and failure behavior. */
public final class ResidentMemoryTest {
public static void main(String[] args) throws Exception {
ResidentMemory reader = new ResidentMemory();
AtomicInteger calls = new AtomicInteger();
CountDownLatch threeReads = new CountDownLatch(3);
Thread caller = Thread.currentThread();
ProcessMemoryMonitor.configure(() -> {
if (Thread.currentThread() == caller) throw new AssertionError("Memory read on recording thread");
long rss = reader.getAsLong();
if (rss <= 0) throw new AssertionError("Native resident memory unavailable on this runner");
calls.incrementAndGet();
threeReads.countDown();
return rss;
});
try {
Thread.sleep(50);
if (calls.get() != 0) throw new AssertionError("Reader ran without a recording");
Recording frames = new Recording("rss", "frames", Path.of("unused"), 10, Map.of());
Recording ticks = new Recording("rss", "ticks", Path.of("unused"), 10, Map.of());
// The third read starts after the second dispatch completed, so both recordings have data.
if (!threeReads.await(10, TimeUnit.SECONDS)) throw new AssertionError("Background reads did not complete");
var frameReport = frames.finish();
var tickReport = ticks.finish();
for (var report : new Recording.Snapshot[]{frameReport, tickReport}) {
var metadata = report.metadata();
long last = (long) metadata.get("process_rss_last_sampled_bytes");
long peak = (long) metadata.get("process_rss_peak_sampled_bytes");
if (last <= 0 || peak < last) throw new AssertionError("Invalid resident memory report");
System.out.println(report.kind() + " RSS last=" + last + " peak=" + peak + " samples=" + metadata.get("process_rss_samples"));
}
int idleCalls = calls.get();
Thread.sleep(1100);
if (calls.get() != idleCalls) throw new AssertionError("Reader kept polling after recordings finished");
CountDownLatch failedRead = new CountDownLatch(1);
ProcessMemoryMonitor.configure(() -> {
failedRead.countDown();
throw new IllegalStateException("Unsupported native reader");
});
Recording unavailable = new Recording("unsupported", "frames", Path.of("unused"), 10, Map.of());
unavailable.add(1_000_000);
if (!failedRead.await(10, TimeUnit.SECONDS)) throw new AssertionError("Unavailable reader was not attempted");
var unavailableReport = unavailable.finish();
if (unavailableReport.samples().length != 1 || unavailableReport.metadata().containsKey("process_rss_peak_sampled_bytes"))
throw new AssertionError("Unavailable memory disrupted recording or was reported as zero");
System.out.println("Background resident-memory checks passed.");
} finally {
ProcessMemoryMonitor.configure(null);
}
}
}
+5 -1
View File
@@ -73,7 +73,11 @@ MEASURE ON YOUR M2 PRO
4. Open Prism's instance Minecraft folder > horizon-benchmarks. Each run writes
frames JSON/CSV and integrated-server ticks JSON/CSV. They include average FPS,
slowest-1%-average FPS, p95/p99 frame durations, stalls, sampled peak JVM heap,
process CPU time and GC data. Heap is sampled once per second during gameplay;
process CPU time, process resident memory (RSS) when available, and GC data.
RSS reads run once per second on a shared background thread during recordings.
They include resident native pages; this is not a complete GPU/unified-memory
measurement. Last RSS is the last sample, not necessarily the finish time.
Heap is sampled once per second during gameplay;
shorter peaks can be missed. CPU measurement spans the whole recording.
Menus, pauses and unfocused frames are excluded. Tick execution time is not
the observed TPS. JVM heap is not whole-process memory or unified GPU memory.
+1 -1
View File
@@ -3,7 +3,7 @@
"minecraft": "26.3",
"java_major": 25,
"fabric_loader": "0.19.5",
"pack_version": "0.5.0",
"pack_version": "0.6.0",
"projects": {
"sodium": {
"slug": "sodium",
+4 -2
View File
@@ -26,7 +26,7 @@
<section id="chartSection" class="section hidden"><div class="chart"><div class="chart-tools"><h2 id="chartTitle">Frame pacing</h2><label><input id="logScale" type="checkbox" checked> Log scale</label></div><div class="legend"><span><i class="dot"></i>Baseline</span><span><i class="dot" style="background:var(--candidate)"></i>Candidate</span></div><svg id="timeline" viewBox="0 0 960 300" role="img" aria-label="Recorded duration timeline"></svg><div id="chartInfo" class="chart-info">Move over the chart to inspect a time bucket.</div><p id="chartNote" class="footnote"></p></div></section>
<p id="csvHint" class="footnote"></p>
</section>
<footer>No installation, account or network access is needed. Repeat at least three matched runs and test fresh terrain separately from a warm cache. JVM memory excludes some native and GPU allocations.</footer>
<footer>No installation, account or network access is needed. Repeat at least three matched runs and test fresh terrain separately from a warm cache. Heap/nonheap exclude native allocations. Process RSS is not a complete GPU/unified-memory measurement.</footer>
</main>
<script>
'use strict';
@@ -79,13 +79,15 @@ function compareReports(a,b){
warnings.push('Tick durations exclude scheduler sleep. Observed TPS includes recording time spent paused; tick execution capacity is not TPS.');
}
add('95th percentile duration','p95Ms','ms',1,true);add('99th percentile duration','p99Ms','ms',1,true);add('Longest duration','maxMs','ms',1,true);
add('Sampled peak process RSS','process_rss_peak_sampled_bytes','MiB',1048576);add('Last sampled process RSS','process_rss_last_sampled_bytes','MiB',1048576);
add('Sampled peak JVM heap','heap_used_peak_sampled_bytes','MiB',1048576);add('JVM heap at end','heap_used_end_bytes','MiB',1048576);
add('Sampled peak nonheap','nonheap_used_peak_sampled_bytes','MiB',1048576);add('Average process CPU','process_cpu_mean_cores','cores');
if(number(a.gc_time_ms)&&number(b.gc_time_ms)){
const av=a.gc_time_ms/a.elapsed_seconds,bv=b.gc_time_ms/b.elapsed_seconds;
rows.push({label:'GC collection time / second',key:'gc_collection_ms_per_second',unit:'ms/s',baseline:av,candidate:bv,change_percent:av?100*(bv/av-1):null});
}
warnings.push('Memory peaks are sampled and can miss short spikes. Heap/nonheap are not process RSS or GPU memory. CPU includes all Java threads and the integrated server.');
warnings.push('Memory peaks are sampled and can miss short spikes. RSS includes resident JVM and native pages, but is not a complete GPU/unified-memory measurement. Heap/nonheap measure JVM pools only. CPU includes the whole process and integrated server.');
for(const [label,r] of [['Baseline',a],['Candidate',b]])if(number(r.process_rss_last_sample_age_ms)&&r.process_rss_last_sample_age_ms>2500)warnings.push(label+' resident-memory sample is '+format(r.process_rss_last_sample_age_ms/1000)+' seconds old. The background reader may be slow or unavailable.');
return{kind:a.kind,differences,warnings,metrics:rows};
}
function renderDetails(side){
+5 -2
View File
@@ -25,7 +25,7 @@ def test_metrics():
destination = BUILD / "metric-tests"
destination.mkdir(parents=True, exist_ok=True)
sources = [SOURCE / "main/java/dev/horizonlab/metrics" / name
for name in ["SampleStats.java", "Recording.java"]]
for name in ["SampleStats.java", "Recording.java", "ProcessMemoryMonitor.java"]]
sources.append(SOURCE / "test/java/dev/horizonlab/metrics/MetricsTest.java")
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.metrics.MetricsTest"], check=True)
@@ -71,9 +71,12 @@ def build():
test_classpath = os.pathsep.join(map(str, [classes, *jars]))
subprocess.run(["javac", "--release", "25", "-proc:none", "-classpath", test_classpath,
"-d", str(adapter_tests),
str(SOURCE / "test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java")], check=True)
str(SOURCE / "test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java"),
str(SOURCE / "test/java/dev/horizonlab/metrics/ResidentMemoryTest.java")], check=True)
subprocess.run(["java", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.client.DistantTerrainBudgetTest"], check=True)
subprocess.run(["java", "--enable-native-access=ALL-UNNAMED", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.metrics.ResidentMemoryTest"], check=True)
output = ROOT / "dist" / f"horizon-lab-{lock['pack_version']}.jar"
output.parent.mkdir(exist_ok=True)
entries = {path.relative_to(classes).as_posix(): path.read_bytes() for path in classes.rglob("*.class")}
+2 -2
View File
@@ -5,7 +5,7 @@ import argparse
import json
from pathlib import Path
MATCH_FIELDS = ("minecraft", "kind", "os", "architecture", "gpu", "graphics_backend", "graphics_driver",
MATCH_FIELDS = ("minecraft", "kind", "os", "os_version", "architecture", "gpu", "graphics_backend", "graphics_driver",
"java_version", "heap_max_bytes", "framebuffer_width", "framebuffer_height", "render_distance",
"simulation_distance", "vsync", "fps_limit", "graphics_preset", "ambient_occlusion",
"improved_transparency", "mipmap_levels", "entity_distance_scaling", "entity_shadows", "particles",
@@ -40,7 +40,7 @@ def compare(baseline, candidate):
rows.append({"metric": key, "baseline": before, "candidate": after,
"change_percent": 100 * (after / before - 1) if before else None})
for key in ["heap_used_end_bytes", "heap_used_peak_sampled_bytes", "nonheap_used_peak_sampled_bytes",
"process_cpu_mean_cores", "gc_time_ms", "observed_ticks_per_second"]:
"process_rss_last_sampled_bytes", "process_rss_peak_sampled_bytes", "process_cpu_mean_cores", "gc_time_ms", "observed_ticks_per_second"]:
if key in baseline and key in candidate:
before, after = baseline[key], candidate[key]
rows.append({"metric": key, "baseline": before, "candidate": after,