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