Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

bench(aot): the loop's speedup is asked what share of a frame it is

yhhd0ae7db6e863
diff --git a/bench/aot-stage0/README.md b/bench/aot-stage0/README.md
index 2f40c476d..70aaa5182 100644
--- a/bench/aot-stage0/README.md
+++ b/bench/aot-stage0/README.md
@@ -74,3 +74,58 @@ build\cmake\aot-stage0\bench_aot_stage0.exe
2. **这量的是系统循环,不是一帧。** 一帧里还有 C++ 的工作、渲染提交、调度本身。
系统循环快 400 倍**不等于**帧快 400 倍 —— Amdahl 说了算。把这个数字翻译成帧预算,
需要先量出「一帧里有多大比例是 TS 系统代码」,那是另一次测量,这里没做。
+
+---
+
+## `frame-share.mjs` —— Amdahl 的分母
+
+上面那个装置量的是**系统循环**。它决定不了任何事:**一个快 400 倍、却只占一帧 5% 的循环,
+只能让帧快 1.05 倍。** Stage 1 真正取决于的是**占比**。
+
+```sh
+node bench/aot-stage0/frame-share.mjs
+BENCH_ENTITIES=20000 node bench/aot-stage0/frame-share.mjs
+```
+
+它启动真实引擎(headless)、打开 SDK 自带的 profiler(`App.enableStats()` 一直在记这些,
+不需要新埋点),读出每个系统的 ms、各 phase 的 ms 和整帧。
+
+**5000 实体 / node 24 / V8:**
+
+| | ms/帧 | 占比 |
+|---|---|---|
+| `VelocitySystem` | 0.92 | 94% |
+| 其余 11 个 TS 系统 | 0.01 | 1.6% |
+| **TS 系统合计** | **0.93** | **95.6%** |
+| 其余(C++/wasm + 调度) | 0.04 | 4.4% |
+
+**一个交叉验证,值得单独说:** 真实的 `VelocitySystem` 在 V8 下 0.92 ms,而 Stage 0 手抄的
+variant A 在 QuickJS 下 10.4–11.8 ms —— **比值 ~12×,是一个合理的解释器/JIT 比**。
+说明 Stage 0 那份对生成访问器的转写没有在量别的东西。
+
+### 但它看不见渲染器,所以它不报一个数字,报一张表
+
+headless 帧里 `rest` 只有 0.04 ms,因为渲染器根本不在。拿它乘 Stage 0 的因子会得到一个
+凯旋的数字,而那是**分母缺失的产物,不是发现**(本文件第一版就打印了一个)。所以改成扫描未知量:
+
+设 `c` = 无 JIT 帧里原生 C++ 的占比,把 TS 那半边编译掉 F 倍后剩 `c + (1-c)/F`:
+
+| C++ 占比 `c` | 帧加速 |
+|---|---|
+| 5% | 19.1× |
+| 20% | 4.95× |
+| **50%** | **1.99×** ← 再往上 AOT 就不是那根杠杆了 |
+| 80% | 1.25× |
+| 95% | 1.05× |
+
+**结论的形状:渲染器的 C++ 得占到无 JIT 帧的一半以上,AOT 才会掉到 2× 以下。**
+无 JIT 下 TS 那半边还会再涨 ~12 倍而 C++ 不变,`c` 只会更小。
+
+### 还欠一次测量
+
+**真实带渲染的一帧里,渲染器的 C++ 花多少。** wasm 构建已经在记
+(`render.collect` / `.submit` / `.graph` / `.finalize`,走 `ES_PROFILE_SCOPE`)。
+
+**原生构建之前记不了** —— `es_profile_now_ms()` 在非 Emscripten 下 `return 0.0`,
+所以那四个 scope 在桌面 / Android / iOS 上**从来就是 0**。没人发现,是因为一个报 0 的
+profiler 看起来就像一个在报「这帧很快」的 profiler。已修(`std::chrono::steady_clock`)。
diff --git a/bench/aot-stage0/frame-share.mjs b/bench/aot-stage0/frame-share.mjs
new file mode 100644
index 000000000..277475687
--- /dev/null
+++ b/bench/aot-stage0/frame-share.mjs
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file frame-share.mjs
+ * @brief Amdahl's denominator for the AOT proposal (docs/REARCH_AOT.md §14).
+ *
+ * @details Stage 0 measured that compiling a system LOOP is worth 154-385x
+ * under a no-JIT interpreter. That decides nothing alone: a loop 400x
+ * faster occupying 5% of a frame moves the frame by 1.05x. What
+ * Stage 1 turns on is the SHARE.
+ *
+ * Boots the real engine headless and reads the split App.enableStats()
+ * has always kept — every system's ms, the phases, the frame. No new
+ * instrumentation.
+ *
+ * Two bounds pull opposite ways, so both are printed:
+ * - it runs under V8 WITH a jit, and the target is an interpreter
+ * where the TS half slows and the C++ half does not, so the share
+ * here is a FLOOR for the native host;
+ * - it is HEADLESS, so the renderer's C++ work is missing and the TS
+ * share is inflated. That is the half still owed.
+ */
+import { existsSync } from 'node:fs';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { dirname, join, resolve } from 'node:path';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO = resolve(HERE, '..', '..');
+
+const ENTITIES = intEnv('BENCH_ENTITIES', 5000);
+const FRAMES = intEnv('BENCH_FRAMES', 300);
+const WARMUP = intEnv('BENCH_WARMUP', 120);
+const DT = 1 / 60;
+
+// What Stage 0 measured for one system loop, QuickJS vs native C++, on the
+// thick/scattered (least flattering) configuration. Used only by the projection.
+const STAGE0_INTERP_FACTOR = 396;
+
+function intEnv(name, def) {
+ const v = process.env[name];
+ if (v == null || v === '') return def;
+ const n = Number(v);
+ return Number.isFinite(n) ? Math.floor(n) : def;
+}
+
+function mulberry32(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a |= 0; a = (a + 0x6D2B79F5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function resolveWasmDir() {
+ const candidates = [
+ process.env.ESENGINE_WASM_DIR && resolve(process.env.ESENGINE_WASM_DIR),
+ join(REPO, 'build', 'wasm', 'web'),
+ join(REPO, 'desktop', 'public', 'wasm'),
+ ].filter(Boolean);
+ for (const dir of candidates) {
+ if (existsSync(join(dir, 'esengine.wasm'))) return dir;
+ }
+ throw new Error('no esengine.wasm — set ESENGINE_WASM_DIR. Tried:\n ' + candidates.join('\n '));
+}
+
+function resolveSdk() {
+ const p = process.env.ESENGINE_SDK
+ ? resolve(process.env.ESENGINE_SDK)
+ : join(REPO, 'sdk', 'dist', 'index.node.js');
+ if (!existsSync(p)) {
+ throw new Error(`no built SDK at ${p} — run \`node build-tools/cli.js sdk\` (add --no-cache after a failed build).`);
+ }
+ return p;
+}
+
+const median = (xs) => {
+ const s = [...xs].sort((a, b) => a - b);
+ return s.length ? s[Math.floor(s.length / 2)] : 0;
+};
+const ms = (x) => x.toFixed(4);
+const pctOf = (x, total) => total > 0 ? (100 * x / total).toFixed(1) + '%' : '—';
+
+async function main() {
+ const wasmDir = resolveWasmDir();
+ const sdkPath = resolveSdk();
+
+ const sdk = await import(pathToFileURL(sdkPath).href);
+ const { loadEsengineModule, createHeadlessApp, Transform, Sprite, Velocity } = sdk;
+
+ const module = await loadEsengineModule(wasmDir);
+ const app = createHeadlessApp(module);
+ app.enableStats();
+ const world = app.world;
+ const cppRegistry = world.getCppRegistry();
+
+ const rand = mulberry32(0x1234abcd);
+ for (let i = 0; i < ENTITIES; i++) {
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x: (rand() - 0.5) * 2000, y: (rand() - 0.5) * 2000, z: 0 } });
+ world.insert(e, Velocity, { linear: { x: (rand() - 0.5) * 120, y: (rand() - 0.5) * 120, z: 0 } });
+ world.insert(e, Sprite, { size: { x: 16, y: 16 } });
+ }
+
+ console.log('='.repeat(70));
+ console.log("Estella AOT — Amdahl's denominator (REARCH_AOT.md §10, Stage 0 follow-up)");
+ console.log(' runtime : node', process.versions.node, '(V8, WITH jit)');
+ console.log(' entities :', ENTITIES);
+ console.log(' frames :', FRAMES, `(+${WARMUP} warmup)`);
+ console.log(' frame : app.tick + transform_update — headless, no renderer');
+ console.log('='.repeat(70));
+
+ const step = async () => {
+ await app.tick(DT);
+ if (cppRegistry) module.transform_update(cppRegistry);
+ };
+
+ for (let f = 0; f < WARMUP; f++) await step();
+
+ // The map read after a tick is already that frame's cost: SystemRunner
+ // accumulates WITHIN a frame and App clears at the boundary. Differencing
+ // snapshots reports zero — which is what the first version of this did.
+ const frameTotals = [];
+ const perSystem = new Map();
+
+ for (let f = 0; f < FRAMES; f++) {
+ const t0 = performance.now();
+ await step();
+ const total = performance.now() - t0;
+
+ const timings = app.getSystemTimings();
+ if (f === 0 && (!timings || timings.size === 0)) {
+ throw new Error('getSystemTimings() is empty after a tick — stats did not take. '
+ + 'enableStats() must be called before the first tick builds the SystemRunner.');
+ }
+ for (const [name, msThisFrame] of timings ?? []) {
+ if (!perSystem.has(name)) perSystem.set(name, []);
+ perSystem.get(name).push(msThisFrame);
+ }
+ frameTotals.push(total);
+ }
+
+ const frame = median(frameTotals);
+ const rows = [...perSystem.entries()]
+ .map(([name, xs]) => ({ name, ms: median(xs) }))
+ .filter((r) => r.ms > 0)
+ .sort((a, b) => b.ms - a.ms);
+ const tsTotal = rows.reduce((a, r) => a + r.ms, 0);
+ const rest = Math.max(0, frame - tsTotal);
+
+ console.log(`\n ${'system (TypeScript)'.padEnd(42)} ${'ms/frame'.padStart(10)} ${'of frame'.padStart(9)}`);
+ console.log(` ${'-'.repeat(42)} ${'-'.repeat(10)} ${'-'.repeat(9)}`);
+ for (const r of rows) {
+ console.log(` ${r.name.padEnd(42)} ${ms(r.ms).padStart(10)} ${pctOf(r.ms, frame).padStart(9)}`);
+ }
+ console.log(` ${'-'.repeat(42)} ${'-'.repeat(10)} ${'-'.repeat(9)}`);
+ console.log(` ${'TS systems, total'.padEnd(42)} ${ms(tsTotal).padStart(10)} ${pctOf(tsTotal, frame).padStart(9)}`);
+ console.log(` ${'everything else (C++/wasm, schedule)'.padEnd(42)} ${ms(rest).padStart(10)} ${pctOf(rest, frame).padStart(9)}`);
+ console.log(` ${'frame'.padEnd(42)} ${ms(frame).padStart(10)} ${'100.0%'.padStart(9)}`);
+
+ const phases = app.getPhaseTimings();
+ if (phases && phases.size) {
+ const ph = [...phases.entries()].filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);
+ if (ph.length) {
+ console.log('\n phases (last frame, for shape — not medians)');
+ for (const [name, v] of ph) console.log(` ${name.padEnd(40)} ${ms(v).padStart(10)}`);
+ }
+ }
+
+ // ----------------------------------------------------------------------
+ // `rest` is 4% only because a headless frame has no renderer, so scaling it
+ // by the Stage 0 factor is an artifact (this printed a 378x once). Sweep the
+ // unknown: for c the C++ share of a no-JIT frame, compiling leaves c+(1-c)/F.
+ // ----------------------------------------------------------------------
+ const share = frame > 0 ? tsTotal / frame : 0;
+ const F = STAGE0_INTERP_FACTOR;
+
+ // Cross-check Stage 0 against the real SDK: its variant A is a hand
+ // transcription of the generated accessors under QuickJS, and this is the
+ // same shape under V8. They must differ by an interpreter/JIT factor, only.
+ const hot = rows[0];
+ if (hot) {
+ console.log('\n cross-check against Stage 0');
+ console.log(` ${hot.name} here, under V8 ......... ${ms(hot.ms)} ms`);
+ console.log(' Stage 0 variant A, under QuickJS ....... 10.4-11.8 ms');
+ console.log(` => QuickJS/V8 on this loop ............. ~${(11.0 / hot.ms).toFixed(0)}x`);
+ console.log(' A plausible interpreter-vs-JIT ratio, so the Stage 0');
+ console.log(' transcription is not measuring something else.');
+ }
+
+ console.log('\n how much C++ must a frame carry before AOT stops paying?');
+ console.log(' ' + '-'.repeat(66));
+ console.log(` F = ${F}x (Stage 0, thick/scattered — what compiling the TS half buys)`);
+ console.log(` ${'C++ share of a no-JIT frame'.padEnd(34)} ${'frame speedup'.padStart(14)}`);
+ for (const c of [0.01, 0.05, 0.2, 0.5, 0.8, 0.95, 0.99]) {
+ const sp = 1 / (c + (1 - c) / F);
+ const note = sp >= 2 ? '' : ' <- AOT no longer the lever';
+ console.log(` ${(100 * c).toFixed(0).padStart(3)}%${' '.repeat(30)} ${(sp.toFixed(2) + 'x').padStart(14)}${note}`);
+ }
+
+ console.log('\n where the measured point sits');
+ console.log(' ' + '-'.repeat(66));
+ console.log(` headless, V8 ....... TS ${(100 * share).toFixed(1)}%, C++ ${(100 * (1 - share)).toFixed(1)}%`);
+ console.log(' Under no-JIT the TS half grows and the C++ half does not, so');
+ console.log(' the C++ share only falls from there. The renderer is the whole');
+ console.log(' of what this cannot see — and it is the only thing that could');
+ console.log(' push c high enough to matter.');
+ console.log('\n NEXT MEASUREMENT: the renderer C++ cost in a real rendered frame.');
+ console.log(' The wasm build already records it (render.collect / .submit / .graph /');
+ console.log(' .finalize via ES_PROFILE_SCOPE). The native build does not — its');
+ console.log(' es_profile_now_ms() returned 0.0 until this branch fixed it.');
+ console.log('='.repeat(70));
+}
+
+main().catch((e) => {
+ console.error('frame-share failed:', e?.stack || e);
+ process.exitCode = 1;
+});
diff --git a/src/esengine/core/FrameProfiler.hpp b/src/esengine/core/FrameProfiler.hpp
index 1f784798e..b6bf1d324 100644
--- a/src/esengine/core/FrameProfiler.hpp
+++ b/src/esengine/core/FrameProfiler.hpp
@@ -11,15 +11,25 @@
#include <cstdio>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
+#else
+#include <chrono>
#endif
namespace esengine {
+/**
+ * Milliseconds from a monotonic origin; only differences mean anything.
+ *
+ * Off Emscripten this returned 0.0 until 2026-08-24, so render.collect,
+ * .submit, .graph and .finalize measured exactly zero on desktop, Android and
+ * iOS — a profiler reporting zero reads as one reporting a fast frame.
+ */
inline double es_profile_now_ms() {
#ifdef __EMSCRIPTEN__
return emscripten_get_now();
#else
- return 0.0;
+ using clock = std::chrono::steady_clock;
+ return std::chrono::duration<double, std::milli>(clock::now().time_since_epoch()).count();
#endif
}