示例工程 37-local-persistence

37-local-persistence/app/shared/bench.ts

typescript · 3.2 KB

import fs from "node:fs";
import path from "node:path";
import { performance } from "node:perf_hooks";
import { writeJsonStore, readJsonStore, type Note } from "./json-store";
import { closeStore, journalMode, openStore, sqliteSize } from "./sqlite-store";

export type BenchResult = {
  count: number;
  json: { writeMs: number; readMs: number; bytes: number };
  sqlite: {
    writeMs: number;
    readMs: number;
    bytes: number;
    journalMode: string;
  };
};

function makeNotes(count: number): Note[] {
  const tail = "持久化基准测试记录:原子写、WAL、索引与文件体积对比。".repeat(
    3,
  );
  return Array.from({ length: count }, (_, index) => ({
    id: `bench-${String(index).padStart(6, "0")}`,
    title: `记录 ${index}`,
    body: `${tail} #${index}`,
    tags: ["bench", index % 2 === 0 ? "even" : "odd"],
    updatedAt: new Date(1_700_000_000_000 + index * 1000).toISOString(),
  }));
}

export function runBenchmark(dir: string, count: number): BenchResult {
  if (!Number.isInteger(count) || count < 100 || count > 20_000) {
    throw new Error("BAD_BENCH_COUNT");
  }
  fs.mkdirSync(dir, { recursive: true });
  const jsonDir = path.join(dir, "json");
  const sqliteFile = path.join(dir, "bench.sqlite");
  for (const file of [
    path.join(jsonDir, "store.json"),
    path.join(jsonDir, "store.json.bak"),
    sqliteFile,
    `${sqliteFile}-wal`,
    `${sqliteFile}-shm`,
  ]) {
    try {
      fs.rmSync(file, { force: true });
    } catch {
      // 清理失败不影响新一轮基准。
    }
  }

  const notes = makeNotes(count);
  const doc = {
    version: 1 as const,
    updatedAt: new Date().toISOString(),
    items: notes,
  };
  const jsonWriteStart = performance.now();
  const written = writeJsonStore(jsonDir, doc);
  const jsonWriteMs = performance.now() - jsonWriteStart;
  const jsonReadStart = performance.now();
  const loaded = readJsonStore(jsonDir);
  const jsonReadMs = performance.now() - jsonReadStart;

  const db = openStore(sqliteFile);
  const insert = db.prepare(
    "INSERT INTO notes (id, title, body, tags, updated_at) VALUES (?, ?, ?, ?, ?)",
  );
  const sqliteWriteStart = performance.now();
  db.exec("BEGIN;");
  try {
    for (const note of notes) {
      insert.run(
        note.id,
        note.title,
        note.body,
        JSON.stringify(note.tags),
        note.updatedAt,
      );
    }
    db.exec("COMMIT;");
  } catch (error) {
    db.exec("ROLLBACK;");
    throw error;
  }
  const sqliteWriteMs = performance.now() - sqliteWriteStart;

  const sqliteReadStart = performance.now();
  const rows = db.prepare("SELECT * FROM notes").all();
  const sqliteReadMs = performance.now() - sqliteReadStart;
  const mode = journalMode(db);
  db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
  closeStore(db);

  if (loaded.doc.items.length !== count || rows.length !== count) {
    throw new Error("BENCH_COUNT_MISMATCH");
  }

  return {
    count,
    json: {
      writeMs: Number(jsonWriteMs.toFixed(2)),
      readMs: Number(jsonReadMs.toFixed(2)),
      bytes: written.bytes,
    },
    sqlite: {
      writeMs: Number(sqliteWriteMs.toFixed(2)),
      readMs: Number(sqliteReadMs.toFixed(2)),
      bytes: sqliteSize(sqliteFile),
      journalMode: mode,
    },
  };
}