diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index c5f8532..050475c 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -23,9 +23,9 @@ No trustworthy tool will produce a maintainable Java port automatically. A decom ## Current status -The binary and source-level consumer audits are complete. Phase 0 still lacks a pre-optimization profile. The -low-coupling Phase 3 queue and the audit-derived immediate compatibility gate are complete. The next milestone is a -focused CPU/allocation baseline before entering measured hot-path work. +The binary and source-level consumer audits, low-coupling Phase 3 queue, audit-derived immediate compatibility gate, +and focused pre-optimization profile are complete. Phase 4 can now begin with the measured `TileMultipart` traversal +path; see `JAVA_MIGRATION_PROFILE.md`. That audit found and this branch has now repaired one existing regression: Schematica 1.12.6 reflects the original private `MultiPartRegistry$` field `codechicken$multipart$MultiPartRegistry$$typeMap` and casts it to a Scala mutable map. The @@ -123,13 +123,18 @@ Exception-table metadata does not impose a meaningful steady-state cost merely b The source and bytecode audit identified allocation patterns that are more plausible performance targets: -- `TileMultipart.updateEntity()` creates a Scala closure for each ticking multipart tile on each tick, then traverses through `operate(Function1)` and Scala collection machinery. -- `TRedstoneTile` power and connection queries create closures and `scala.runtime.IntRef` boxes in frequently queried code. +- The Java port's `TileMultipart.updateEntity()` still traverses through `operate(Function1)`, whose current + `parts()` helper materializes an `ArrayList`, backing array, Scala iterator and Java-conversion wrappers per call. +- `TRedstoneTile` power and connection queries create closures and `scala.runtime.IntRef` boxes in frequently queried + code. - Several Scala 2.11 collection, range, and `JavaConversions` paths create closure objects, boxed primitives, iterators, or temporary collections. - `TSlottedTile.canAddPart` and several `MicroRecipe` searches use exception-based non-local returns. - Rendering code in `TileMultipart` already uses cached arrays and `while` loops in important paths. It should be preserved as evidence of deliberate optimization, not mechanically rewritten into streams or higher-level collection pipelines. -These are static findings, not proof of their share of frame or tick time. Capture profiles and allocation data before and after each relevant migration phase. +The focused Forge/JFR baseline confirms both risks. With eight parts, `updateEntity` and `operate` allocate about 184 +bytes per call, while a three-query redstone iteration allocates 80.5 bytes. CPU samples identify the same collection, +boxing and closure paths. These are focused measurements, not whole-pack TPS; retain the workload and re-profile after +each relevant migration phase. See `JAVA_MIGRATION_PROFILE.md`. ### Runtime code generation is architectural, not incidental @@ -249,7 +254,8 @@ If a characterization test captures a confirmed bug that the port intentionally - [x] Add a separate Forge integration-test source set/runner for behavior that cannot execute in a plain JVM. - [x] Write the first characterization suite against the untouched Scala implementation. - [x] Create a remaining manual compatibility checklist for rendering, input, and other behavior that cannot be asserted reliably by the automated harness. See `JAVA_MIGRATION_MANUAL_CHECKS.md`. -- [ ] Capture representative CPU and allocation profiles before optimization work. +- [x] Capture representative CPU and allocation profiles before optimization work. See + `JAVA_MIGRATION_PROFILE.md`. - [x] Start a divergence log. Exit condition: there is a reproducible behavior and ABI baseline, the test layers run in CI or an equivalent repeatable command, and the initial suite passes against the Scala implementation. @@ -323,10 +329,11 @@ and the already-ported registry again supports Schematica. - [ ] Use fastutil only where profiling and data shape justify it. - [ ] Re-profile the same scenarios and record both improvements and regressions. -Status: not started. This phase does not begin until the immediate compatibility gate and an initial profile are -complete. The first sensible implementation unit is the whole `IRedstonePart.scala` file: its six related traits and -load-bearing `RedstoneInteractions$` must be characterized and ported together. Do not optimize `TileMultipart` -storage merely because the source audit found allocations; its list/order/lifecycle contracts must be frozen first. +Status: ready to start. The compatibility gate and initial profile are complete. First freeze `operate` behavior when +callbacks add or remove parts, then remove the measured per-traversal `ArrayList`/array/wrapper materialization while +retaining the public Scala `Seq` and `operate(Function1)` ABI. Re-run the focused profile immediately. The next broader +unit is the whole `IRedstonePart.scala` file: its six related traits and load-bearing `RedstoneInteractions$` must be +characterized and ported together. Exit condition: identified steady-state Scala allocation sites are removed with compatible results. @@ -631,4 +638,8 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec - Froze a server-only pass-through interface with primitive/reference overloads. The generated tile forwards to one implementing part, rejects a second implementor, preserves and rebinds its delegate through `copyFrom`, and clears the generated implementation field on removal. +- Added an opt-in Forge/JFR workload and captured the first focused CPU/allocation baseline. With eight parts, + `updateEntity` and `operate` allocate 184.0 and 183.9 bytes per call; generated redstone's three-query iteration + allocates 80.5 bytes. CPU and allocation sites point to `TileMultipart.parts()` collection copies and Scala + redstone `IntRef`/closure traversal. Full methodology and rerun commands are in `JAVA_MIGRATION_PROFILE.md`. - The expanded baseline is 130 plain-JVM tests and 28 Forge server tests, all passing. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index 6ceb3f7..76af5f1 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -662,8 +662,10 @@ same messages, since Scala's `assert` is always enabled here and Java's is not. `partList` remains a `scala.collection.immutable.List` published through `partList()Lscala/collection/Seq;`, which five jars link against. Mutations copy to a Java list, mutate, and republish through `JavaConversions`, matching the -reference's allocate-a-new-Seq semantics exactly. No performance decision is taken here; that is Phase 4 work and -needs profiling first. +reference's allocate-a-new-Seq semantics exactly. The focused Phase 4 baseline later found that the Java port's +`parts()` read helper also materializes an `ArrayList`, backing array, iterator and conversion wrappers on every +traversal. That read-side cost is not required by the reference and is the next measured optimization target; see +`JAVA_MIGRATION_PROFILE.md`. `operate` keeps its `(Lscala/Function1;)V` descriptor and internal callers still go through it, wrapping their action in an `AbstractFunction1`. That preserves both the virtual dispatch, so any trait overriding `operate` still sees diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 48493a6..6a4648d 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -10,8 +10,9 @@ what breaks, and what is left. The other documents hold the reasoning. | `JAVA_MIGRATION_CONSUMER_AUDIT.md` | How every consumer uses FMP at runtime: data, lifecycle, reflection, and generated tiles | | `JAVA_MIGRATION_DIVERGENCES.md` | Every intentional difference from the reference, one entry per port | | `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client | +| `JAVA_MIGRATION_PROFILE.md` | The focused pre-optimization baseline, findings, and exact rerun command | -Branch: `algent/java`. Base: `master`. 54 commits so far. +Branch: `algent/java`. Base: `master`. 62 commits including the profile-baseline commit. ## The one rule that matters @@ -47,6 +48,14 @@ test, and if you do adjust it, re-run it against the stashed Scala to prove the ./gradlew runFunctionalTestServer ``` +Focused CPU/allocation profile from PowerShell: + +```powershell +.\gradlew.bat runFunctionalTestServer "-Pforgemultipart.profileFunctionalTests=true" +``` + +See `JAVA_MIGRATION_PROFILE.md` before comparing its ignored `.jfr` and text outputs. + Test result counts (the Gradle output does not print them): ```bash @@ -211,9 +220,14 @@ The immediate compatibility gate is complete. `ForgeEnvironmentSmokeTest` now fr trait generation, Java-trait rewriting/dispatch, generated-class reuse, and a server-only pass-through interface's overloads, single-implementor rule, copy/rebind behavior, and removal cleanup. -Next capture a focused CPU/allocation baseline for `TileMultipart.updateEntity`, `TileMultipart.operate`, and redstone -queries. Use the measurements to select the first Phase 4 change rather than assuming the statically visible -allocations dominate. +The focused CPU/allocation baseline is complete. It measures about 184 allocated bytes per eight-part +`updateEntity`/`operate` call and 80.5 bytes per generated redstone three-query iteration. JFR attributes the first pair +to `TileMultipart.parts()` collection conversion/copying and the redstone path to Scala iteration, `IntRef`, and +generated closures. Full results and rerun commands are in `JAVA_MIGRATION_PROFILE.md`. + +Next freeze `operate` behavior when callbacks add or remove parts, then remove its measured per-call collection +materialization without changing the Scala `Seq`/`Function1` ABI. Re-run the same profile before starting the complete +`IRedstonePart.scala` unit. `IRedstonePart.scala` is misleadingly named and is **not** a marker-trait file. It holds six traits plus `RedstoneInteractions`, whose `MODULE$` is load-bearing. After the compatibility gate and an initial profile, port the @@ -235,13 +249,14 @@ all of `multipart/asm/`. The ASM subsystem should be last; freeze generated-clas - The full manual checklist has not been completed. Limited smoke testing has been performed in the GTNH full pack, but individual checklist items remain unrecorded and unverified. Every port since `TCuboidPart` has deferred something to it, and `BlockMultipart` leans on it hardest: breaking, selection boxes, collision, pick block, activation, particles and light are covered by nothing automated. Run it in a real client before this branch goes near a release. -- No CPU or allocation profiles exist. Phase 4 has not started, so there is no baseline to compare against. +- The focused synthetic baseline exists, but a representative full-GTNH-pack CPU/allocation capture is still manual + work and is required before release claims about real TPS. - The server side of flag-sensitive pass-through registration is automated; client-side exclusion still belongs to the packaged-client/manual compatibility run. - Microblock-specific NBT and packet payloads still need characterization immediately before that subsystem changes; the compact core tile/part fixture is complete. -- `TileMultipart`'s `partList` still republishes an immutable Scala `Seq` on every mutation, and `operate` still - allocates a `Function1` per call. Both are faithful to the reference and both are deliberately left for Phase 4, - which needs profiling first. +- `TileMultipart`'s `partList` still republishes an immutable Scala `Seq` on every mutation. The Java port's `parts()` + additionally materializes an `ArrayList` and backing array per traversal; the profile confirms it as the first Phase + 4 target. Preserve the reference's captured-immutable-sequence mutation behavior while removing that port artifact. - Phase 1 never properly started. GTNHLib is currently commented out in `dependencies.gradle`; it had been added at `api` scope to satisfy a test compile rather than because a migration change needed it. diff --git a/JAVA_MIGRATION_MANUAL_CHECKS.md b/JAVA_MIGRATION_MANUAL_CHECKS.md index 096a552..e22c396 100644 --- a/JAVA_MIGRATION_MANUAL_CHECKS.md +++ b/JAVA_MIGRATION_MANUAL_CHECKS.md @@ -46,5 +46,6 @@ release that includes those ports. ## Not yet covered anywhere -- CPU and allocation profiles before and after the hot-path work. Phase 4 has not started, so no baseline exists. +- A focused pre-optimization CPU/allocation baseline now exists in `JAVA_MIGRATION_PROFILE.md`. A representative + full-pack capture and the matching post-optimization comparison still need to be performed. - NBT and packet layout fixtures beyond the material id carrier. Phase 0 still lists this as open. diff --git a/JAVA_MIGRATION_PROFILE.md b/JAVA_MIGRATION_PROFILE.md new file mode 100644 index 0000000..ba147af --- /dev/null +++ b/JAVA_MIGRATION_PROFILE.md @@ -0,0 +1,82 @@ +# Java migration — focused performance baseline + +This is the reproducible pre-optimization baseline for Phase 4. It runs inside the real deobfuscated Forge dedicated +server, using the same generated tiles as the functional suite. It is intentionally focused rather than a claim about +whole-pack TPS. + +## Re-run + +The local server EULA must already contain `eula=true`. From PowerShell at the repository root: + +```powershell +.\gradlew.bat runFunctionalTestServer "-Pforgemultipart.profileFunctionalTests=true" +``` + +The property is quoted because PowerShell otherwise splits the dotted Gradle property. Normal +`runFunctionalTestServer` runs remain unchanged. Profile mode overwrites these ignored files: + +- `run/server/forgemultipart-profile.txt` — exact timings and per-thread allocation counts; +- `run/server/forgemultipart-baseline.jfr` — JFR CPU, allocation-site, and GC events. + +Useful JDK commands after the run: + +```powershell +Get-Content run/server/forgemultipart-profile.txt +jfr summary run/server/forgemultipart-baseline.jfr +jfr view --width 220 hot-methods run/server/forgemultipart-baseline.jfr +jfr view thread-allocation run/server/forgemultipart-baseline.jfr +``` + +Open the `.jfr` in Java Mission Control for flame graphs and allocation-site inspection. The `startEpochMillis` and +`nanos` values in the text file define the exact time window for each phase. Java 8 recordings expose TLAB allocation +events rather than the newer `ObjectAllocationSample`, so `jfr view allocation-by-site` from a recent JDK is not a +valid summary of this recording. + +## Workload + +The fixture uses Zulu OpenJDK 8, eight parts per tile, 1,000,000 warm-up iterations, then 50,000,000 measured +iterations per phase: + +- `updateEntity`: one `TileMultipart.updateEntity()` call, dispatching `update()` to eight ticking parts; +- `operate`: one `TileMultipart.operate(Function1)` call with one reused function and eight bound parts; +- `redstoneQueries`: one `strongPowerLevel`, one `getConnectionMask`, and one masked `weakPowerLevel` call on a + generated `TRedstoneTile` containing eight `IRedstonePart` implementations. + +The checksum consumes all observable work. Allocation bytes come from HotSpot's per-thread allocation counter, not +from sampled JFR events. JFR remains the source for CPU samples and allocation-site ranking. + +## Baseline captured 2026-08-27 + +Environment: Zulu 8.96 / OpenJDK `1.8.0_504-b01`, Windows 11, 16 hardware threads, `-Xms1G -Xmx4G`, JFR `profile` +settings. + +| Phase | Elapsed | Operations/s | Allocated bytes | Bytes/operation | CPU samples | +| --- | ---: | ---: | ---: | ---: | ---: | +| `updateEntity` | 2.970 s | 16,835,622 | 9,198,500,864 | 184.0 | 209 | +| `operate` | 3.004 s | 16,646,549 | 9,195,084,824 | 183.9 | 205 | +| `redstoneQueries` | 3.689 s | 13,553,242 | 4,023,003,032 | 80.5 | 239 | + +Timing is machine- and JIT-sensitive; compare it only with the same workload and environment. Allocation per operation +is the more stable regression metric. + +### CPU and allocation-site findings + +- `updateEntity` and `operate` are dominated by `TileMultipart.parts()`, `AbstractCollection.toArray`, Scala list + length/iteration, and Java-conversion wrappers. Their nearly identical 184-byte allocation cost shows that the + traversal snapshot, not the update callback itself, is the first target. +- The current Java `parts()` constructs an `ArrayList` from the published Scala `Seq` on every traversal. The reference + Scala `operate` captured the immutable `Seq` and iterated it directly, so this cost is a port artifact rather than a + compatibility requirement. +- Redstone CPU samples are concentrated in Scala `List.foreach` (118/239), `PartMap.edgeBetween` (46/239), iterator + `foreach` (35/239), and the generated strong-power closure (31/239). Allocation events identify + `scala.runtime.IntRef`, Scala iterators, and generated closures as the major sites. + +## Decision + +The first Phase 4 implementation should target `TileMultipart` traversal, but only after one focused test freezes its +mutation semantics: iteration observes the captured part order, skips a part whose tile was cleared before its turn, +and does not visit a part added during the callback. Then remove the per-call `ArrayList`/array/wrapper materialization +while retaining the public Scala `Seq` and `operate(Function1)` ABI, and re-run this exact profile. + +After that comparison, characterize and port the complete `IRedstonePart.scala` unit and eliminate the measured +redstone `IntRef`/closure paths without splitting its load-bearing `RedstoneInteractions$` singleton. diff --git a/addon.gradle b/addon.gradle index 5d76383..9e0eaa3 100644 --- a/addon.gradle +++ b/addon.gradle @@ -35,7 +35,11 @@ tasks.register(functionalTestSet.jarTaskName, Jar) { def functionalTestRunProperty = "forgemultipart.withFunctionalTests" def withFunctionalTests = providers.gradleProperty(functionalTestRunProperty).map { it.toBoolean() }.orElse(false).get() +def profileRunProperty = "forgemultipart.profileFunctionalTests" +def profileFunctionalTests = providers.gradleProperty(profileRunProperty).map { it.toBoolean() }.orElse(false).get() def functionalTestReportDirectory = layout.projectDirectory.dir("run/server/junit-out") +def functionalTestProfileRecording = layout.projectDirectory.file("run/server/forgemultipart-baseline.jfr") +def functionalTestProfileResults = layout.projectDirectory.file("run/server/forgemultipart-profile.txt") def addFunctionalTestsToRun = { JavaExec task -> task.dependsOn(functionalTestSet.jarTaskName) task.classpath( @@ -48,9 +52,15 @@ tasks.register("runFunctionalTestServer", GradleBuild) { description = "Runs the Java 8 Forge server with the ForgeMultipart functional test mod" setTasks(["runServer"]) startParameter.projectProperties.put(functionalTestRunProperty, "true") + if (profileFunctionalTests) { + startParameter.projectProperties.put(profileRunProperty, "true") + } doFirst { delete(functionalTestReportDirectory) + if (profileFunctionalTests) { + delete(functionalTestProfileRecording, functionalTestProfileResults) + } } doLast { def reports = fileTree(functionalTestReportDirectory).matching { include("TEST-*.xml") }.files @@ -71,6 +81,10 @@ tasks.register("runFunctionalTestServer", GradleBuild) { throw new GradleException( "ForgeMultipart functional tests failed: ${tests} tests, ${failures} failures, ${errors} errors") } + if (profileFunctionalTests + && (!functionalTestProfileRecording.asFile.isFile() || !functionalTestProfileResults.asFile.isFile())) { + throw new GradleException("ForgeMultipart profile produced incomplete output") + } } } @@ -78,6 +92,12 @@ if (withFunctionalTests) { tasks.withType(JavaExec).configureEach { task -> if (task.name == "runServer") { addFunctionalTestsToRun(task) + if (profileFunctionalTests) { + task.jvmArgs( + "-XX:+FlightRecorder", + "-XX:StartFlightRecording=filename=forgemultipart-baseline.jfr,settings=profile,dumponexit=true") + task.systemProperty(profileRunProperty, "true") + } } } } diff --git a/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java index 6436537..45c5301 100644 --- a/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java +++ b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java @@ -72,6 +72,10 @@ public final class ForgeMultipartFunctionalTestMod { MinecraftServer server = MinecraftServer.getServer(); server.addChatMessage(new ChatComponentText("Running ForgeMultipart functional tests...")); + if (Boolean.getBoolean("forgemultipart.profileFunctionalTests")) { + ForgeMultipartProfileWorkload.run(); + } + TestExecutionSummary summary = runTests(); if (summary.getTestsFoundCount() == 0) { throw new IllegalStateException("No ForgeMultipart functional tests were discovered"); diff --git a/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartProfileWorkload.java b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartProfileWorkload.java new file mode 100644 index 0000000..6e8f127 --- /dev/null +++ b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartProfileWorkload.java @@ -0,0 +1,213 @@ +package codechicken.multipart.test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.lang.management.ManagementFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import codechicken.multipart.IRedstonePart; +import codechicken.multipart.IRedstoneTile; +import codechicken.multipart.MultipartHelper; +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TileMultipart; +import scala.runtime.AbstractFunction1; +import scala.runtime.BoxedUnit; + +/** Fixed workload used only by the opt-in JFR baseline run. */ +final class ForgeMultipartProfileWorkload { + + private static final int PART_COUNT = 8; + private static final int WARMUP_ITERATIONS = 1_000_000; + private static final int PROFILE_ITERATIONS = 50_000_000; + private static volatile long sink; + + private ForgeMultipartProfileWorkload() {} + + static void run() { + List tickingParts = new ArrayList<>(); + for (int i = 0; i < PART_COUNT; i++) { + tickingParts.add(new ProfilePart()); + } + TileMultipart tickingTile = MultipartHelper.createTileFromParts(tickingParts); + + List redstoneParts = new ArrayList<>(); + for (int i = 0; i < PART_COUNT; i++) { + redstoneParts.add(new RedstoneProfilePart(i)); + } + TileMultipart redstoneTile = MultipartHelper.createTileFromParts(redstoneParts); + IRedstoneTile redstone = (IRedstoneTile) redstoneTile; + CountingFunction operation = new CountingFunction(); + com.sun.management.ThreadMXBean allocationBean = allocationBean(); + long threadId = Thread.currentThread().getId(); + + profileUpdateEntity(tickingTile, WARMUP_ITERATIONS); + profileOperate(tickingTile, operation, WARMUP_ITERATIONS); + profileRedstone(redstoneTile, redstone, WARMUP_ITERATIONS); + + long updateStartMillis = System.currentTimeMillis(); + long updateStartBytes = allocationBean.getThreadAllocatedBytes(threadId); + long updateStart = System.nanoTime(); + profileUpdateEntity(tickingTile, PROFILE_ITERATIONS); + long updateNanos = System.nanoTime() - updateStart; + long updateBytes = allocationBean.getThreadAllocatedBytes(threadId) - updateStartBytes; + + long operateStartMillis = System.currentTimeMillis(); + long operateStartBytes = allocationBean.getThreadAllocatedBytes(threadId); + long operateStart = System.nanoTime(); + profileOperate(tickingTile, operation, PROFILE_ITERATIONS); + long operateNanos = System.nanoTime() - operateStart; + long operateBytes = allocationBean.getThreadAllocatedBytes(threadId) - operateStartBytes; + + long redstoneStartMillis = System.currentTimeMillis(); + long redstoneStartBytes = allocationBean.getThreadAllocatedBytes(threadId); + long redstoneStart = System.nanoTime(); + long redstoneChecksum = profileRedstone(redstoneTile, redstone, PROFILE_ITERATIONS); + long redstoneNanos = System.nanoTime() - redstoneStart; + long redstoneBytes = allocationBean.getThreadAllocatedBytes(threadId) - redstoneStartBytes; + + long updateChecksum = 0; + for (TMultiPart part : tickingParts) { + updateChecksum += ((ProfilePart) part).updates; + } + sink = updateChecksum + operation.applications + redstoneChecksum; + writeResults( + updateStartMillis, + updateNanos, + updateBytes, + operateStartMillis, + operateNanos, + operateBytes, + redstoneStartMillis, + redstoneNanos, + redstoneBytes, + sink); + } + + private static void profileUpdateEntity(TileMultipart tile, int iterations) { + for (int i = 0; i < iterations; i++) { + tile.updateEntity(); + } + } + + private static void profileOperate(TileMultipart tile, CountingFunction operation, int iterations) { + for (int i = 0; i < iterations; i++) { + tile.operate(operation); + } + } + + private static long profileRedstone(TileMultipart tile, IRedstoneTile redstone, int iterations) { + long checksum = 0; + for (int i = 0; i < iterations; i++) { + int side = i % 6; + checksum += tile.strongPowerLevel(side); + checksum += redstone.getConnectionMask(side); + checksum += redstone.weakPowerLevel(side, 0x1F); + } + return checksum; + } + + private static void writeResults(long updateStartMillis, long updateNanos, long updateBytes, + long operateStartMillis, long operateNanos, long operateBytes, long redstoneStartMillis, long redstoneNanos, + long redstoneBytes, long checksum) { + File output = new File("forgemultipart-profile.txt"); + try (PrintWriter writer = new PrintWriter(output)) { + writer.printf(Locale.ROOT, "java=%s%n", System.getProperty("java.runtime.version")); + writer.printf(Locale.ROOT, "parts=%d%n", PART_COUNT); + writer.printf(Locale.ROOT, "warmupIterations=%d%n", WARMUP_ITERATIONS); + writer.printf(Locale.ROOT, "profileIterations=%d%n", PROFILE_ITERATIONS); + writeTiming(writer, "updateEntity", updateStartMillis, updateNanos, updateBytes); + writeTiming(writer, "operate", operateStartMillis, operateNanos, operateBytes); + writeTiming(writer, "redstoneQueries", redstoneStartMillis, redstoneNanos, redstoneBytes); + writer.printf(Locale.ROOT, "checksum=%d%n", checksum); + } catch (FileNotFoundException e) { + throw new IllegalStateException("Could not write ForgeMultipart profile results", e); + } + } + + private static void writeTiming(PrintWriter writer, String name, long startMillis, long nanos, + long allocatedBytes) { + double seconds = nanos / 1_000_000_000d; + writer.printf(Locale.ROOT, "%s.startEpochMillis=%d%n", name, startMillis); + writer.printf(Locale.ROOT, "%s.nanos=%d%n", name, nanos); + writer.printf(Locale.ROOT, "%s.operationsPerSecond=%.0f%n", name, PROFILE_ITERATIONS / seconds); + writer.printf(Locale.ROOT, "%s.allocatedBytes=%d%n", name, allocatedBytes); + writer.printf( + Locale.ROOT, + "%s.allocatedBytesPerOperation=%.1f%n", + name, + allocatedBytes / (double) PROFILE_ITERATIONS); + } + + private static com.sun.management.ThreadMXBean allocationBean() { + java.lang.management.ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + if (!(bean instanceof com.sun.management.ThreadMXBean)) { + throw new IllegalStateException("The profiling JVM does not expose thread allocation counters"); + } + com.sun.management.ThreadMXBean allocationBean = (com.sun.management.ThreadMXBean) bean; + if (!allocationBean.isThreadAllocatedMemorySupported()) { + throw new IllegalStateException("The profiling JVM does not support thread allocation counters"); + } + if (!allocationBean.isThreadAllocatedMemoryEnabled()) { + allocationBean.setThreadAllocatedMemoryEnabled(true); + } + return allocationBean; + } + + private static class ProfilePart extends TMultiPart { + + private int updates; + + @Override + public String getType() { + return "profile_part"; + } + + @Override + public boolean doesTick() { + return true; + } + + @Override + public void update() { + updates++; + } + } + + private static final class RedstoneProfilePart extends ProfilePart implements IRedstonePart { + + private final int power; + + private RedstoneProfilePart(int power) { + this.power = power; + } + + @Override + public int strongPowerLevel(int side) { + return power + side; + } + + @Override + public int weakPowerLevel(int side) { + return power + side; + } + + @Override + public boolean canConnectRedstone(int side) { + return true; + } + } + + private static final class CountingFunction extends AbstractFunction1 { + + private long applications; + + @Override + public BoxedUnit apply(TMultiPart part) { + applications++; + return BoxedUnit.UNIT; + } + } +}