* 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 = ITERATIONS)
| 17 | * @returns {Object} Performance results |
| 18 | */ |
| 19 | function benchmark(testName, testFunction, iterations = ITERATIONS) { |
| 20 | // Warmup |
| 21 | for (let i = 0; i < WARMUP_ITERATIONS; i++) { |
| 22 | testFunction(); |
| 23 | } |
| 24 | |
| 25 | if (global.gc) { |
| 26 | global.gc(); |
| 27 | } |
| 28 | |
| 29 | const startTime = process.hrtime.bigint(); |
| 30 | |
| 31 | for (let i = 0; i < iterations; i++) { |
| 32 | testFunction(); |
| 33 | } |
| 34 | |
| 35 | const endTime = process.hrtime.bigint(); |
| 36 | const totalTime = Number(endTime - startTime) / 1000000; |
| 37 | const avgTime = totalTime / iterations; |
| 38 | const opsPerSecond = Math.round(1000 / avgTime); |
| 39 | |
| 40 | return { |
| 41 | testName, |
| 42 | iterations, |
| 43 | totalTime: totalTime.toFixed(2), |
| 44 | avgTime: avgTime.toFixed(6), |
| 45 | opsPerSecond, |
| 46 | relativeSpeed: 1, |
| 47 | }; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Prints benchmark results with comparison analysis |