* Runs a performance test for a given function * @param {string} testName - Name of the test * @param {Function} testFunction - Function to benchmark * @param {number} iterations - Number of iterations to run * @returns {Object} Performance results
(testName, testFunction, iterations = STRESS_ITERATIONS)
| 17 | * @returns {Object} Performance results |
| 18 | */ |
| 19 | function benchmark(testName, testFunction, iterations = STRESS_ITERATIONS) { |
| 20 | // Warmup |
| 21 | for (let i = 0; i < WARMUP_ITERATIONS; i++) { |
| 22 | try { |
| 23 | testFunction(); |
| 24 | } catch { |
| 25 | // Ignore warmup errors |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | if (global.gc) { |
| 30 | global.gc(); |
| 31 | } |
| 32 | |
| 33 | let successCount = 0; |
| 34 | let errorCount = 0; |
| 35 | |
| 36 | const startTime = process.hrtime.bigint(); |
| 37 | |
| 38 | for (let i = 0; i < iterations; i++) { |
| 39 | try { |
| 40 | testFunction(); |
| 41 | successCount++; |
| 42 | } catch { |
| 43 | errorCount++; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | const endTime = process.hrtime.bigint(); |
| 48 | const totalTime = Number(endTime - startTime) / 1000000; |
| 49 | const avgTime = totalTime / iterations; |
| 50 | const opsPerSecond = Math.round(1000 / avgTime); |
| 51 | |
| 52 | return { |
| 53 | testName, |
| 54 | iterations, |
| 55 | successCount, |
| 56 | errorCount, |
| 57 | totalTime: totalTime.toFixed(2), |
| 58 | avgTime: avgTime.toFixed(6), |
| 59 | opsPerSecond, |
| 60 | successRate: ((successCount / iterations) * 100).toFixed(1), |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Generates random test values |