profile-test-files.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Per-file profiler for finding candidate test-speed work; see ../../perf/test-suite.md
  2. // for the benchmark notes, kept wins, and discarded experiments.
  3. // Example: TEST_PROFILE_GLOB='test/server/**/*.test.ts' TEST_PROFILE_TOP=15 bun run profile:test
  4. const pattern = Bun.env.TEST_PROFILE_GLOB ?? "test/**/*.test.{ts,tsx}"
  5. const limit = Number(Bun.env.TEST_PROFILE_LIMIT ?? 0)
  6. const timeout = Bun.env.TEST_PROFILE_TIMEOUT ?? "30000"
  7. const files = Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: import.meta.dir + "/..", onlyFiles: true }))
  8. .then((files) => files.toSorted())
  9. .then((files) => (limit > 0 ? files.slice(0, limit) : files))
  10. const results = []
  11. for (const file of await files) {
  12. const start = performance.now()
  13. const proc = Bun.spawn(["bun", "test", "--timeout", timeout, file], {
  14. cwd: import.meta.dir + "/..",
  15. stdout: "pipe",
  16. stderr: "pipe",
  17. env: Bun.env,
  18. })
  19. const [output, error, exitCode] = await Promise.all([
  20. new Response(proc.stdout).text(),
  21. new Response(proc.stderr).text(),
  22. proc.exited,
  23. ])
  24. const seconds = (performance.now() - start) / 1000
  25. results.push({ file, seconds, exitCode })
  26. console.log(`${exitCode === 0 ? "PASS" : "FAIL"} ${seconds.toFixed(3)}s ${file}`)
  27. if (exitCode !== 0) console.log((output + error).trim())
  28. }
  29. const sorted = results.toSorted((a, b) => b.seconds - a.seconds)
  30. console.log("\nSlowest test files:")
  31. for (const result of sorted.slice(0, Number(Bun.env.TEST_PROFILE_TOP ?? 20))) {
  32. console.log(`${result.seconds.toFixed(3)}s ${result.exitCode === 0 ? "PASS" : "FAIL"} ${result.file}`)
  33. }
  34. if (sorted[0]) {
  35. console.log(`METRIC slowest_test_file_seconds=${sorted[0].seconds.toFixed(3)}`)
  36. console.log(`METRIC profiled_test_files=${results.length}`)
  37. }
  38. if (results.some((result) => result.exitCode !== 0)) process.exit(1)