Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

17.5 KB
Raw Blame
// Reproducible apples-to-apples benchmark: ThreeRT (`threert-wallpaper`) vs Chromium WebView
// running the EXACT same three.js WebGPURenderer + TSL wallpaper bundle (`out/webgpu/wallpaper-demo.js`).
//
// Measures:
//   - Binary & runtime footprint
//   - Process-tree PSS & RSS memory (MiB) via /proc/<pid>/smaps_rollup
//   - Process-tree CPU% via /proc/<pid>/stat
//   - Voluntary + involuntary context switches / sec (wakeups/s)
//   - Intel iGPU active residency % (100 - Δrc6_residency_ms / Δwall_ms) & avg MHz (rps_act_freq_mhz)
//   - Cold-start Time-To-First-Frame (TTFF ms)
//   - Occluded-desktop idle power / CPU / wakeups (ThreeRT auto-pause vs Chromium)
//
// Usage: node webgpu/wallpaper/bench/bench.mjs [--out <dir>] [--duration 15]
import { spawn, spawnSync } from "node:child_process";
import { createServer } from "node:http";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const benchDir = import.meta.dirname;
const root = join(benchDir, "..", "..", "..");
const outArgIdx = process.argv.indexOf("--out");
const outDir = outArgIdx >= 0 ? process.argv[outArgIdx + 1] : join(root, "out", "webgpu", "wallpaper-bench");
const durArgIdx = process.argv.indexOf("--duration");
const MEASURE_SEC = durArgIdx >= 0 ? Math.max(5, parseFloat(process.argv[durArgIdx + 1])) : 15;
const WARMUP_SEC = 4;

mkdirSync(outDir, { recursive: true });

const wallpaperBin = join(root, "webgpu", "wallpaper", "target", "release", "threert-wallpaper");
const runtimeJs = join(root, "out", "webgpu", "runtime.js");
const demoJs = join(root, "out", "webgpu", "wallpaper-demo.js");
const demoHtml = join(root, "out", "webgpu", "wallpaper-demo.html");
const CLK_TCK = 100; // Linux x86_64 USER_HZ

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function findDrmGtPath() {
  try {
    for (const card of readdirSync("/sys/class/drm")) {
      const p = `/sys/class/drm/${card}/gt/gt0`;
      if (existsSync(join(p, "rc6_residency_ms"))) return p;
    }
  } catch {}
  return null;
}

const DRM_GT = findDrmGtPath();

function readRc6Ms() {
  if (!DRM_GT) return null;
  try {
    return parseInt(readFileSync(join(DRM_GT, "rc6_residency_ms"), "utf8").trim(), 10);
  } catch {
    return null;
  }
}

function readGpuFreqMhz() {
  if (!DRM_GT) return null;
  try {
    return parseInt(readFileSync(join(DRM_GT, "rps_act_freq_mhz"), "utf8").trim(), 10);
  } catch {
    return null;
  }
}

function readBatteryPowerW() {
  try {
    const status = readFileSync("/sys/class/power_supply/BAT0/status", "utf8").trim();
    const uw = parseInt(readFileSync("/sys/class/power_supply/BAT0/power_now", "utf8").trim(), 10);
    return { status, watts: Number.isFinite(uw) ? uw / 1e6 : null };
  } catch {
    return { status: "unknown", watts: null };
  }
}

/** Collect all PIDs belonging to `rootPid`'s process tree (plus any Chromium helpers matching `tag`). */
function collectTreePids(rootPid, cmdTag = null) {
  const children = new Map();
  const tagged = new Set();
  for (const name of readdirSync("/proc")) {
    if (!/^\d+$/.test(name)) continue;
    const pid = parseInt(name, 10);
    try {
      const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
      const rparen = stat.lastIndexOf(")");
      if (rparen < 0) continue;
      const fields = stat.slice(rparen + 2).split(" ");
      const ppid = parseInt(fields[1], 10);
      if (!children.has(ppid)) children.set(ppid, []);
      children.get(ppid).push(pid);
      if (cmdTag) {
        const cmdline = readFileSync(`/proc/${pid}/cmdline`, "utf8");
        if (cmdline.includes(cmdTag)) tagged.add(pid);
      }
    } catch {}
  }
  const visited = new Set();
  const queue = [rootPid, ...tagged];
  while (queue.length > 0) {
    const p = queue.shift();
    if (visited.has(p)) continue;
    if (!existsSync(`/proc/${p}`)) continue;
    visited.add(p);
    for (const c of children.get(p) || []) queue.push(c);
  }
  return [...visited];
}

function sampleProcTree(rootPid, cmdTag = null) {
  const pids = collectTreePids(rootPid, cmdTag);
  let pssKb = 0;
  let rssKb = 0;
  let cpuTicks = 0;
  let ctxtSwitches = 0;
  let threads = 0;
  for (const pid of pids) {
    try {
      const smaps = readFileSync(`/proc/${pid}/smaps_rollup`, "utf8");
      const mPss = /^Pss:\s+(\d+)/m.exec(smaps);
      const mRss = /^Rss:\s+(\d+)/m.exec(smaps);
      if (mPss) pssKb += parseInt(mPss[1], 10);
      if (mRss) rssKb += parseInt(mRss[1], 10);
    } catch {}
    try {
      const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
      const rparen = stat.lastIndexOf(")");
      if (rparen >= 0) {
        const fields = stat.slice(rparen + 2).split(" ");
        cpuTicks += parseInt(fields[11], 10) + parseInt(fields[12], 10); // utime + stime
        threads += parseInt(fields[17], 10);
      }
    } catch {}
    try {
      const status = readFileSync(`/proc/${pid}/status`, "utf8");
      const v = /^voluntary_ctxt_switches:\s+(\d+)/m.exec(status);
      const nv = /^nonvoluntary_ctxt_switches:\s+(\d+)/m.exec(status);
      if (v) ctxtSwitches += parseInt(v[1], 10);
      if (nv) ctxtSwitches += parseInt(nv[1], 10);
    } catch {}
  }
  return {
    procCount: pids.length,
    threads,
    pssMiB: pssKb / 1024,
    rssMiB: rssKb / 1024,
    cpuTicks,
    ctxtSwitches,
  };
}

function median(arr) {
  if (!arr.length) return 0;
  const s = [...arr].sort((a, b) => a - b);
  return s[Math.floor(s.length / 2)];
}

function avg(arr) {
  return arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
}

async function measureBaseline(sec = 8) {
  console.log(`\n[bench] Measuring idle desktop baseline (${sec}s)...`);
  const rc6Start = readRc6Ms();
  const t0 = performance.now();
  const freqs = [];
  const endAt = t0 + sec * 1000;
  while (performance.now() < endAt) {
    const f = readGpuFreqMhz();
    if (f !== null) freqs.push(f);
    await sleep(250);
  }
  const wallMs = performance.now() - t0;
  const rc6End = readRc6Ms();
  const gpuActivePct =
    rc6Start !== null && rc6End !== null
      ? Math.max(0, Math.min(100, 100 * (1 - (rc6End - rc6Start) / wallMs)))
      : null;
  const res = {
    wallMs,
    gpuActivePct: gpuActivePct !== null ? +gpuActivePct.toFixed(2) : null,
    gpuAvgMhz: +avg(freqs).toFixed(1),
    battery: readBatteryPowerW(),
  };
  console.log("[bench] Baseline:", JSON.stringify(res));
  return res;
}

async function measureProcess(label, spawnFn, { warmupSec = WARMUP_SEC, measureSec = MEASURE_SEC, cmdTag = null } = {}) {
  console.log(`\n[bench] Running: ${label} (warmup ${warmupSec}s + measure ${measureSec}s)...`);
  const { proc, cleanup, extra } = spawnFn();
  let exited = false;
  let stderrBuf = "";
  proc.stderr?.on("data", (d) => {
    stderrBuf += d.toString();
  });
  proc.on("exit", () => {
    exited = true;
  });

  await sleep(warmupSec * 1000);
  if (exited) {
    cleanup?.();
    throw new Error(`${label} exited during warmup:\n${stderrBuf}`);
  }

  const s0 = sampleProcTree(proc.pid, cmdTag);
  const rc6Start = readRc6Ms();
  const t0 = performance.now();

  const pssSamples = [];
  const rssSamples = [];
  const procCountSamples = [];
  const threadSamples = [];
  const freqSamples = [];
  let prevTicks = s0.cpuTicks;
  let prevCtxt = s0.ctxtSwitches;
  let totalDeltaTicks = 0;
  let totalDeltaCtxt = 0;

  const endAt = t0 + measureSec * 1000;
  let step = 0;
  while (performance.now() < endAt && !exited) {
    await sleep(250);
    step++;
    const f = readGpuFreqMhz();
    if (f !== null) freqSamples.push(f);
    if (step % 4 === 0) {
      const s = sampleProcTree(proc.pid, cmdTag);
      pssSamples.push(s.pssMiB);
      rssSamples.push(s.rssMiB);
      procCountSamples.push(s.procCount);
      threadSamples.push(s.threads);
      if (s.cpuTicks >= prevTicks) totalDeltaTicks += s.cpuTicks - prevTicks;
      if (s.ctxtSwitches >= prevCtxt) totalDeltaCtxt += s.ctxtSwitches - prevCtxt;
      prevTicks = s.cpuTicks;
      prevCtxt = s.ctxtSwitches;
    }
  }

  const wallMs = performance.now() - t0;
  const rc6End = readRc6Ms();
  const sEnd = sampleProcTree(proc.pid, cmdTag);
  if (sEnd.cpuTicks >= prevTicks) totalDeltaTicks += sEnd.cpuTicks - prevTicks;
  if (sEnd.ctxtSwitches >= prevCtxt) totalDeltaCtxt += sEnd.ctxtSwitches - prevCtxt;

  // Terminate cleanly and wait for exit
  try {
    proc.kill("SIGTERM");
  } catch {}
  for (let i = 0; i < 30 && !exited; i++) await sleep(100);
  if (!exited) {
    try {
      proc.kill("SIGKILL");
    } catch {}
    await sleep(300);
  }
  cleanup?.();

  const cpuPct = ((totalDeltaTicks / CLK_TCK) / (wallMs / 1000)) * 100;
  const wakeupsPerSec = totalDeltaCtxt / (wallMs / 1000);
  const gpuActivePct =
    rc6Start !== null && rc6End !== null
      ? Math.max(0, Math.min(100, 100 * (1 - (rc6End - rc6Start) / wallMs)))
      : null;

  const result = {
    label,
    wallSec: +(wallMs / 1000).toFixed(2),
    procCount: Math.round(median(procCountSamples)),
    threads: Math.round(median(threadSamples)),
    pssMiB: +median(pssSamples).toFixed(1),
    pssPeakMiB: +(pssSamples.length ? Math.max(...pssSamples) : 0).toFixed(1),
    rssMiB: +median(rssSamples).toFixed(1),
    cpuPct: +cpuPct.toFixed(2),
    wakeupsPerSec: +wakeupsPerSec.toFixed(1),
    gpuActivePct: gpuActivePct !== null ? +gpuActivePct.toFixed(2) : null,
    gpuAvgMhz: +avg(freqSamples).toFixed(1),
    extra: extra?.(stderrBuf) ?? {},
  };
  console.log(`[bench] ${label}:`, JSON.stringify(result));
  return result;
}

async function startStaticServer() {
  const mime = { ".html": "text/html", ".js": "application/javascript", ".jpg": "image/jpeg", ".png": "image/png" };
  const assetsDir = join(root, "out", "webgpu", "assets");
  const server = createServer((req, res) => {
    const urlPath = (req.url || "/").split("?")[0];
    let target = demoHtml;
    if (urlPath === "/wallpaper-demo.js") {
      target = demoJs;
    } else if (urlPath.startsWith("/assets/")) {
      const rel = urlPath.slice("/assets/".length);
      if (rel && !rel.includes("..") && !rel.includes("/")) {
        target = join(assetsDir, rel);
      }
    }
    try {
      const body = readFileSync(target);
      const ext = target.slice(target.lastIndexOf("."));
      res.writeHead(200, { "Content-Type": mime[ext] || "application/octet-stream" });
      res.end(body);
    } catch {
      res.writeHead(404);
      res.end("not found");
    }
  });
  await new Promise((r) => server.listen(0, "127.0.0.1", r));
  const port = server.address().port;
  return { server, port };
}

function spawnThreeRT(extraArgs, statsFile) {
  const args = [
    "--runtime", runtimeJs,
    "--script", demoJs,
    "--layer", "background",
    "--omarchy",
    "--stats-json", statsFile,
    ...extraArgs,
  ];
  const proc = spawn(wallpaperBin, args, { stdio: ["ignore", "pipe", "pipe"] });
  return {
    proc,
    cleanup: () => {},
    extra: () => {
      try {
        return JSON.parse(readFileSync(statsFile, "utf8"));
      } catch {
        return {};
      }
    },
  };
}

function spawnChromium(port, query, { extraFlags = [] } = {}) {
  const prof = mkdtempSync(join(tmpdir(), "threert-bench-chr-"));
  const tag = prof.split("/").pop();
  const url = `http://127.0.0.1:${port}/wallpaper-demo.html?${query}`;
  const args = [
    `--user-data-dir=${prof}`,
    "--ozone-platform=wayland",
    "--enable-unsafe-webgpu",
    "--enable-features=Vulkan",
    "--no-first-run",
    "--no-default-browser-check",
    "--disable-extensions",
    "--disable-background-networking",
    "--disable-sync",
    "--disable-component-update",
    "--disable-features=TranslateUI",
    "--window-size=1440,900",
    `--app=${url}`,
    ...extraFlags,
  ];
  const proc = spawn("chromium", args, { stdio: ["ignore", "pipe", "pipe"] });
  return {
    proc,
    cmdTag: tag,
    cleanup: () => {
      try {
        rmSync(prof, { recursive: true, force: true });
      } catch {}
    },
    extra: (stderr) => {
      const m = /WALLPAPER_READY backend=(\S+) ttff_ms=([\d.]+)(?: canvas=(\S+))?/.exec(stderr);
      const fpsMatches = [...stderr.matchAll(/WALLPAPER_FPS fps=([\d.]+) frames=(\d+) canvas=(\S+)/g)];
      const fpsVals = fpsMatches.map((x) => parseFloat(x[1]));
      const lastCanvas = fpsMatches.length ? fpsMatches[fpsMatches.length - 1][3] : (m?.[3] ?? null);
      return {
        backend: m?.[1] ?? null,
        pageTtffMs: m ? parseFloat(m[2]) : null,
        canvas: lastCanvas,
        achievedFps: fpsVals.length ? +median(fpsVals).toFixed(1) : null,
      };
    },
  };
}

async function measureColdStartTTFF(port, runs = 3) {
  console.log(`\n[bench] Measuring Cold-Start TTFF (${runs} runs each)...`);
  const trtRuns = [];
  for (let i = 0; i < runs; i++) {
    const sf = join(outDir, `ttff-trt-${i}.json`);
    const res = spawnSync(
      wallpaperBin,
      ["--runtime", runtimeJs, "--script", demoJs, "--layer", "background", "--omarchy", "--no-occlusion-pause", "--duration", "2.0", "--stats-json", sf],
      { encoding: "utf8" },
    );
    try {
      const j = JSON.parse(readFileSync(sf, "utf8"));
      if (typeof j.ttff_ms === "number") trtRuns.push(+j.ttff_ms.toFixed(1));
    } catch {
      console.error("TTFF parse failed:", res.stderr);
    }
    await sleep(400);
  }

  const chrRuns = [];
  for (let i = 0; i < runs; i++) {
    const prof = mkdtempSync(join(tmpdir(), "threert-ttff-chr-"));
    const t0 = performance.now();
    const proc = spawn(
      "chromium",
      [
        `--user-data-dir=${prof}`,
        "--ozone-platform=wayland",
        "--enable-unsafe-webgpu",
        "--enable-features=Vulkan",
        "--no-first-run",
        "--disable-extensions",
        "--disable-background-networking",
        "--disable-sync",
        "--enable-logging=stderr",
        "--v=0",
        "--window-size=1440,900",
        `--app=http://127.0.0.1:${port}/wallpaper-demo.html?fps=60&dpr=1.5`,
      ],
      { stdio: ["ignore", "pipe", "pipe"] },
    );
    const ttff = await new Promise((resolve) => {
      let done = false;
      const timer = setTimeout(() => {
        if (!done) {
          done = true;
          resolve(null);
        }
      }, 15000);
      proc.stderr.on("data", (d) => {
        const s = d.toString();
        if (!done && s.includes("WALLPAPER_READY")) {
          done = true;
          clearTimeout(timer);
          resolve(+(performance.now() - t0).toFixed(1));
        }
      });
      proc.on("exit", () => {
        if (!done) {
          done = true;
          clearTimeout(timer);
          resolve(null);
        }
      });
    });
    try {
      proc.kill("SIGTERM");
    } catch {}
    await sleep(600);
    try {
      proc.kill("SIGKILL");
    } catch {}
    rmSync(prof, { recursive: true, force: true });
    if (ttff !== null) chrRuns.push(ttff);
    await sleep(500);
  }
  const out = {
    threertRunsMs: trtRuns,
    threertMedianMs: +median(trtRuns).toFixed(1),
    chromiumRunsMs: chrRuns,
    chromiumMedianMs: +median(chrRuns).toFixed(1),
  };
  console.log("[bench] Cold-Start TTFF:", JSON.stringify(out));
  return out;
}

async function main() {
  if (!existsSync(wallpaperBin)) {
    throw new Error(`Missing ${wallpaperBin}; build threert-wallpaper first.`);
  }
  const binSizeMiB = +(statSync(wallpaperBin).size / (1024 * 1024)).toFixed(2);
  let chromiumBinMiB = null;
  try {
    chromiumBinMiB = +(statSync("/usr/lib/chromium/chromium").size / (1024 * 1024)).toFixed(1);
  } catch {}

  const { server, port } = await startStaticServer();
  try {
    const baseline = await measureBaseline(8);
    const ttff = await measureColdStartTTFF(port, 3);

    // 1. Active Desktop 60 FPS (AC profile, exact 2160x1350)
    const trt60 = await measureProcess(
      "ThreeRT 60fps (2160x1350)",
      () => spawnThreeRT(["--no-occlusion-pause", "--fps", "60", "--render-scale", "1.0"], join(outDir, "trt-60.json")),
    );
    await sleep(1500);
    const chr60 = await measureProcess(
      "Chromium 60fps (2160x1350)",
      () => spawnChromium(port, "fps=60&w=1440&h=900&dpr=1.5", { extraFlags: ["--enable-logging=stderr", "--v=0"] }),
      { cmdTag: "threert-bench-chr-" },
    );
    await sleep(1500);

    // 2. Battery 30 FPS (exact 1620x1012 on BOTH ThreeRT and Chromium)
    const trt30 = await measureProcess(
      "ThreeRT 30fps Battery (1620x1012)",
      () => spawnThreeRT(["--no-occlusion-pause", "--fps", "30", "--render-scale", "0.75"], join(outDir, "trt-30.json")),
    );
    await sleep(1500);
    const chr30 = await measureProcess(
      "Chromium 30fps (1620x1012)",
      () => spawnChromium(port, "fps=30&w=1440&h=900&dpr=1.125", { extraFlags: ["--enable-logging=stderr", "--v=0"] }),
      { cmdTag: "threert-bench-chr-" },
    );
    await sleep(1500);

    // 3. Occluded Desktop (ThreeRT auto-paused by Hyprland vs Chromium background)
    const trtPaused = await measureProcess(
      "ThreeRT Occluded (Auto-Paused 0fps)",
      () => spawnThreeRT(["--force-paused", "--fps", "60"], join(outDir, "trt-paused.json")),
    );

    const summary = {
      timestamp: new Date().toISOString(),
      host: {
        display: "2160x1350 @ 60Hz (logical 1440x900, scale 1.5)",
        threertBinaryMiB: binSizeMiB,
        chromiumBinaryMiB: chromiumBinMiB,
        demoBundleKiB: +(statSync(demoJs).size / 1024).toFixed(1),
        runtimeBundleKiB: +(statSync(runtimeJs).size / 1024).toFixed(1),
      },
      baseline,
      ttff,
      scenarios: { trt60, chr60, trt30, chr30, trtPaused },
    };

    const jsonPath = join(outDir, "results.json");
    writeFileSync(jsonPath, JSON.stringify(summary, null, 2));
    console.log(`\n[bench] Wrote full results to ${jsonPath}`);
  } finally {
    server.close();
  }
}

main().catch((e) => {
  console.error("[bench] FAILED:", e);
  process.exit(1);
});