|
| 1 | +/** |
| 2 | + * 🐝 bee-threads Benchmark Suite |
| 3 | + * |
| 4 | + * Run with: |
| 5 | + * bun benchmarks.js |
| 6 | + * node benchmarks.js |
| 7 | + * |
| 8 | + * Compares: main thread vs turbo |
| 9 | + * Measures: execution time, CPU usage |
| 10 | + */ |
| 11 | + |
| 12 | +const os = require('os'); |
| 13 | +const { bee, beeThreads } = require('./dist/index.js'); |
| 14 | + |
| 15 | +const cpus = os.cpus().length; |
| 16 | +const runtime = typeof Bun !== 'undefined' ? 'Bun' : 'Node'; |
| 17 | + |
| 18 | +// Config - Adjust based on your system |
| 19 | +const SIZE = 1_000_000; |
| 20 | +const RUNS = 10; // Number of runs for averaging |
| 21 | + |
| 22 | +// Heavy function (CPU intensive) |
| 23 | +const heavyFn = (x) => { |
| 24 | + let v = x; |
| 25 | + for (let i = 0; i < 10; i++) { |
| 26 | + v = Math.sqrt(Math.abs(Math.sin(v) * 1000)); |
| 27 | + } |
| 28 | + return v; |
| 29 | +}; |
| 30 | + |
| 31 | +// CPU usage measurement |
| 32 | +function getCpuUsage() { |
| 33 | + const usage = process.cpuUsage(); |
| 34 | + return { |
| 35 | + user: usage.user / 1000, |
| 36 | + system: usage.system / 1000 |
| 37 | + }; |
| 38 | +} |
| 39 | + |
| 40 | +async function benchmark(name, fn) { |
| 41 | + const times = []; |
| 42 | + const cpuTimes = []; |
| 43 | + |
| 44 | + // Warmup run |
| 45 | + await fn(); |
| 46 | + |
| 47 | + // Measured runs |
| 48 | + for (let run = 0; run < RUNS; run++) { |
| 49 | + const cpuStart = getCpuUsage(); |
| 50 | + const start = performance.now(); |
| 51 | + |
| 52 | + await fn(); |
| 53 | + |
| 54 | + const elapsed = performance.now() - start; |
| 55 | + const cpuEnd = getCpuUsage(); |
| 56 | + const cpuUsed = (cpuEnd.user - cpuStart.user) + (cpuEnd.system - cpuStart.system); |
| 57 | + |
| 58 | + times.push(elapsed); |
| 59 | + cpuTimes.push(cpuUsed); |
| 60 | + } |
| 61 | + |
| 62 | + // Calculate stats |
| 63 | + const avg = arr => arr.reduce((a, b) => a + b, 0) / arr.length; |
| 64 | + const stdDev = arr => { |
| 65 | + const mean = avg(arr); |
| 66 | + return Math.sqrt(arr.reduce((sum, x) => sum + (x - mean) ** 2, 0) / arr.length); |
| 67 | + }; |
| 68 | + |
| 69 | + const ms = avg(times); |
| 70 | + const msStd = stdDev(times); |
| 71 | + const cpu = avg(cpuTimes); |
| 72 | + // CPU usage as percentage: (total CPU time / elapsed time) * 100 |
| 73 | + // >100% means multiple cores were used |
| 74 | + const cpuUsage = (cpu / ms) * 100; |
| 75 | + |
| 76 | + return { name, ms, msStd, cpu, cpuUsage }; |
| 77 | +} |
| 78 | + |
| 79 | +async function main() { |
| 80 | + console.log(` |
| 81 | +╔═══════════════════════════════════════════════════════════════╗ |
| 82 | +║ 🐝 bee-threads Benchmark Suite ║ |
| 83 | +╠═══════════════════════════════════════════════════════════════╣ |
| 84 | +║ Runtime: ${runtime.padEnd(10)} │ CPUs: ${String(cpus).padEnd(4)} │ Array: ${(SIZE/1e6).toFixed(1)}M items ║ |
| 85 | +║ Function: Heavy (Math.sqrt + Math.sin × 10 iterations) ║ |
| 86 | +╚═══════════════════════════════════════════════════════════════╝ |
| 87 | +`); |
| 88 | + |
| 89 | + const arr = new Array(SIZE).fill(0).map((_, i) => i); |
| 90 | + const results = []; |
| 91 | + |
| 92 | + // 1) Main thread |
| 93 | + console.log('⏳ Testing main thread...'); |
| 94 | + results.push(await benchmark('main', () => { |
| 95 | + arr.map(heavyFn); |
| 96 | + })); |
| 97 | + |
| 98 | + // 2) bee() - single worker |
| 99 | + console.log('⏳ Testing bee()...'); |
| 100 | + try { |
| 101 | + const beeResult = await Promise.race([ |
| 102 | + benchmark('bee', async () => { |
| 103 | + await bee((data) => { |
| 104 | + return data.map(x => { |
| 105 | + let v = x; |
| 106 | + for (let i = 0; i < 10; i++) v = Math.sqrt(Math.abs(Math.sin(v) * 1000)); |
| 107 | + return v; |
| 108 | + }); |
| 109 | + })(arr); |
| 110 | + }), |
| 111 | + new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 120000)) |
| 112 | + ]); |
| 113 | + results.push(beeResult); |
| 114 | + } catch (e) { |
| 115 | + console.log(' ⚠️ bee() timed out or failed'); |
| 116 | + results.push({ name: 'bee', ms: Infinity, msStd: 0, cpu: 0, cpuUsage: 0 }); |
| 117 | + } |
| 118 | + |
| 119 | + // 3) turbo with different worker counts |
| 120 | + const workerConfigs = [4, 8, cpus]; |
| 121 | + if (cpus > 8) workerConfigs.push(cpus + 4); |
| 122 | + for (const workers of workerConfigs) { |
| 123 | + console.log(`⏳ Testing turbo(${workers})...`); |
| 124 | + try { |
| 125 | + const result = await Promise.race([ |
| 126 | + benchmark(`turbo(${workers})`, async () => { |
| 127 | + await beeThreads.turbo(arr, { workers, force: true }).map(heavyFn); |
| 128 | + }), |
| 129 | + new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 60000)) |
| 130 | + ]); |
| 131 | + results.push(result); |
| 132 | + } catch (e) { |
| 133 | + console.log(` ⚠️ turbo(${workers}) timed out`); |
| 134 | + results.push({ name: `turbo(${workers})`, ms: Infinity, msStd: 0, cpu: 0, cpuUsage: 0 }); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + // Print results |
| 139 | + const mainMs = results[0].ms; |
| 140 | + |
| 141 | + console.log(` |
| 142 | +┌─────────────┬────────────────┬─────────┬─────────────┐ |
| 143 | +│ Mode │ Time (±std) │ vs Main │ Main Thread │ |
| 144 | +├─────────────┼────────────────┼─────────┼─────────────┤`); |
| 145 | + |
| 146 | + for (const r of results) { |
| 147 | + const speedup = (mainMs / r.ms).toFixed(2); |
| 148 | + const marker = parseFloat(speedup) >= 1 ? '✅' : ' '; |
| 149 | + const timeStr = `${r.ms.toFixed(0)}±${r.msStd.toFixed(0)}ms`; |
| 150 | + const blocking = r.name === 'main' ? '❌ blocked' : '✅ free'; |
| 151 | + console.log(`│ ${r.name.padEnd(11)} │ ${timeStr.padStart(14)} │ ${speedup.padStart(5)}x ${marker}│ ${blocking.padEnd(11)} │`); |
| 152 | + } |
| 153 | + |
| 154 | + console.log(`└─────────────┴────────────────┴─────────┴─────────────┘`); |
| 155 | + console.log(`\n 📈 Stats: ${RUNS} runs per config (+ 1 warmup)`); |
| 156 | + |
| 157 | + // Summary |
| 158 | + const best = results.slice(1).reduce((a, b) => a.ms < b.ms ? a : b); |
| 159 | + const bestSpeedup = (mainMs / best.ms).toFixed(2); |
| 160 | + |
| 161 | + console.log(` |
| 162 | +📊 Summary: |
| 163 | + • Best turbo config: ${best.name} (${bestSpeedup}x vs main) |
| 164 | + • Recommended: turbo(${cpus}) for this system |
| 165 | + |
| 166 | +💡 Customize workers: |
| 167 | + beeThreads.turbo(arr).setWorkers(${cpus}).map(fn) |
| 168 | +`); |
| 169 | + |
| 170 | + await beeThreads.shutdown(); |
| 171 | +} |
| 172 | + |
| 173 | +main().catch(console.error); |
| 174 | + |
0 commit comments