|
| 1 | +import { Pool } from 'pg' |
| 2 | + |
| 3 | +const pool = new Pool({ |
| 4 | + connectionString: process.env.DATABASE_URL, |
| 5 | +}) |
| 6 | + |
| 7 | +type BenchmarkResult = { |
| 8 | + name: string |
| 9 | + duration: number |
| 10 | + operations: number |
| 11 | + opsPerSecond: number |
| 12 | + memoryUsed: number |
| 13 | +} |
| 14 | + |
| 15 | +async function updatePlayerMmrIndividual( |
| 16 | + queueId: number, |
| 17 | + userId: string, |
| 18 | + newElo: number, |
| 19 | + newVolatility: number, |
| 20 | +): Promise<void> { |
| 21 | + const clampedElo = Math.max(0, Math.min(9999, newElo)) |
| 22 | + await pool.query( |
| 23 | + `UPDATE queue_users SET elo = $1, peak_elo = GREATEST(peak_elo, $1), volatility = $2 WHERE user_id = $3 AND queue_id = $4`, |
| 24 | + [clampedElo, newVolatility, userId, queueId], |
| 25 | + ) |
| 26 | +} |
| 27 | + |
| 28 | +async function updatePlayerMmrBulk( |
| 29 | + queueId: number, |
| 30 | + updates: Array<{ user_id: string; elo: number; volatility: number }>, |
| 31 | +): Promise<void> { |
| 32 | + if (updates.length === 0) return |
| 33 | + |
| 34 | + const values = updates.flatMap((u) => [ |
| 35 | + u.elo, |
| 36 | + u.volatility, |
| 37 | + u.user_id, |
| 38 | + queueId, |
| 39 | + ]) |
| 40 | + |
| 41 | + const placeholders = updates |
| 42 | + .map((_, i) => { |
| 43 | + const offset = i * 4 |
| 44 | + return `($${offset + 1}, $${offset + 2}, $${offset + 3}, $${offset + 4})` |
| 45 | + }) |
| 46 | + .join(', ') |
| 47 | + |
| 48 | + await pool.query( |
| 49 | + `UPDATE queue_users AS qu |
| 50 | + SET elo = v.elo::numeric, |
| 51 | + peak_elo = GREATEST(qu.peak_elo, v.elo::numeric), |
| 52 | + volatility = v.volatility::integer |
| 53 | + FROM (VALUES ${placeholders}) AS v(elo, volatility, user_id, queue_id) |
| 54 | + WHERE qu.user_id = v.user_id::text AND qu.queue_id = v.queue_id::integer`, |
| 55 | + values, |
| 56 | + ) |
| 57 | +} |
| 58 | + |
| 59 | +async function benchmark( |
| 60 | + name: string, |
| 61 | + fn: () => Promise<void>, |
| 62 | + operations: number, |
| 63 | + iterations: number = 1, |
| 64 | +): Promise<BenchmarkResult> { |
| 65 | + const startMem = process.memoryUsage().heapUsed |
| 66 | + const durations: number[] = [] |
| 67 | + |
| 68 | + for (let i = 0; i < iterations; i++) { |
| 69 | + const start = performance.now() |
| 70 | + await fn() |
| 71 | + const end = performance.now() |
| 72 | + durations.push(end - start) |
| 73 | + } |
| 74 | + |
| 75 | + const endMem = process.memoryUsage().heapUsed |
| 76 | + const avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length |
| 77 | + |
| 78 | + return { |
| 79 | + name, |
| 80 | + duration: avgDuration, |
| 81 | + operations, |
| 82 | + opsPerSecond: (operations / avgDuration) * 1000, |
| 83 | + memoryUsed: endMem - startMem, |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +async function getExistingPlayers( |
| 88 | + queueId: number, |
| 89 | + limit: number, |
| 90 | +): Promise<string[]> { |
| 91 | + const result = await pool.query( |
| 92 | + `SELECT user_id FROM queue_users WHERE queue_id = $1 LIMIT $2`, |
| 93 | + [queueId, limit], |
| 94 | + ) |
| 95 | + return result.rows.map((row) => row.user_id) |
| 96 | +} |
| 97 | + |
| 98 | +async function getQueueId(): Promise<number> { |
| 99 | + const result = await pool.query(`SELECT id FROM queues LIMIT 1`) |
| 100 | + if (result.rows.length === 0) { |
| 101 | + throw new Error('No queues found in database') |
| 102 | + } |
| 103 | + return result.rows[0].id |
| 104 | +} |
| 105 | + |
| 106 | +async function runBenchmark( |
| 107 | + name: string, |
| 108 | + queueId: number, |
| 109 | + playerCount: number, |
| 110 | + method: 'individual' | 'bulk', |
| 111 | + iterations: number = 3, |
| 112 | +): Promise<BenchmarkResult> { |
| 113 | + console.log(`\nRunning: ${name}...`) |
| 114 | + |
| 115 | + const userIds = await getExistingPlayers(queueId, playerCount) |
| 116 | + |
| 117 | + if (userIds.length < playerCount) { |
| 118 | + console.log(`⚠ Only found ${userIds.length} players, using that instead`) |
| 119 | + } |
| 120 | + |
| 121 | + const result = await benchmark( |
| 122 | + name, |
| 123 | + async () => { |
| 124 | + if (method === 'individual') { |
| 125 | + for (const userId of userIds) { |
| 126 | + await updatePlayerMmrIndividual( |
| 127 | + queueId, |
| 128 | + userId, |
| 129 | + 1000 + Math.random() * 50, |
| 130 | + Math.floor(Math.random() * 10), |
| 131 | + ) |
| 132 | + } |
| 133 | + } else { |
| 134 | + const updates = userIds.map((userId) => ({ |
| 135 | + user_id: userId, |
| 136 | + elo: 1000 + Math.random() * 50, |
| 137 | + volatility: Math.floor(Math.random() * 10), |
| 138 | + })) |
| 139 | + await updatePlayerMmrBulk(queueId, updates) |
| 140 | + } |
| 141 | + }, |
| 142 | + userIds.length, |
| 143 | + iterations, |
| 144 | + ) |
| 145 | + |
| 146 | + console.log( |
| 147 | + `✓ Completed: ${result.duration.toFixed(2)}ms (${result.opsPerSecond.toFixed(2)} ops/sec)`, |
| 148 | + ) |
| 149 | + return result |
| 150 | +} |
| 151 | + |
| 152 | +async function main() { |
| 153 | + console.log('=== MMR Update Benchmark ===\n') |
| 154 | + console.log('Warming up connection...\n') |
| 155 | + |
| 156 | + await pool.query('SELECT 1') |
| 157 | + |
| 158 | + const queueId = await getQueueId() |
| 159 | + console.log(`Using queue_id: ${queueId}`) |
| 160 | + |
| 161 | + const totalPlayers = await pool.query( |
| 162 | + `SELECT COUNT(*) FROM queue_users WHERE queue_id = $1`, |
| 163 | + [queueId], |
| 164 | + ) |
| 165 | + console.log(`Total players in queue: ${totalPlayers.rows[0].count}`) |
| 166 | + console.log('Iterations per test: 3\n') |
| 167 | + |
| 168 | + const results: BenchmarkResult[] = [] |
| 169 | + |
| 170 | + const testCases = [ |
| 171 | + { players: 10, label: '10 players' }, |
| 172 | + { players: 50, label: '50 players' }, |
| 173 | + { players: 100, label: '100 players' }, |
| 174 | + { players: 500, label: '500 players' }, |
| 175 | + { players: 1000, label: '1000 players' }, |
| 176 | + ] |
| 177 | + |
| 178 | + for (const testCase of testCases) { |
| 179 | + results.push( |
| 180 | + await runBenchmark( |
| 181 | + `${testCase.label} - individual`, |
| 182 | + queueId, |
| 183 | + testCase.players, |
| 184 | + 'individual', |
| 185 | + ), |
| 186 | + ) |
| 187 | + |
| 188 | + results.push( |
| 189 | + await runBenchmark( |
| 190 | + `${testCase.label} - bulk`, |
| 191 | + queueId, |
| 192 | + testCase.players, |
| 193 | + 'bulk', |
| 194 | + ), |
| 195 | + ) |
| 196 | + } |
| 197 | + |
| 198 | + console.log('\n\n=== Results ===\n') |
| 199 | + console.table( |
| 200 | + results.map((r) => ({ |
| 201 | + Test: r.name, |
| 202 | + 'Avg Duration (ms)': r.duration.toFixed(2), |
| 203 | + Ops: r.operations, |
| 204 | + 'Ops/sec': r.opsPerSecond.toFixed(2), |
| 205 | + 'Memory (KB)': (r.memoryUsed / 1024).toFixed(2), |
| 206 | + })), |
| 207 | + ) |
| 208 | + |
| 209 | + console.log('\n=== Performance Comparison ===\n') |
| 210 | + for (let i = 0; i < results.length; i += 2) { |
| 211 | + const individual = results[i] |
| 212 | + const bulk = results[i + 1] |
| 213 | + const speedup = individual.duration / bulk.duration |
| 214 | + |
| 215 | + console.log(`${individual.name.split(' - ')[0]}:`) |
| 216 | + console.log(` Bulk is ${speedup.toFixed(2)}x faster`) |
| 217 | + console.log( |
| 218 | + ` Time saved: ${(individual.duration - bulk.duration).toFixed(2)}ms`, |
| 219 | + ) |
| 220 | + console.log( |
| 221 | + ` Memory diff: ${((bulk.memoryUsed - individual.memoryUsed) / 1024).toFixed(2)}KB\n`, |
| 222 | + ) |
| 223 | + } |
| 224 | + |
| 225 | + await pool.end() |
| 226 | + console.log('Benchmark complete.') |
| 227 | +} |
| 228 | + |
| 229 | +main().catch((error) => { |
| 230 | + console.error('Benchmark failed:', error) |
| 231 | + pool.end().finally(() => process.exit(1)) |
| 232 | +}) |
0 commit comments