| 28 | } |
| 29 | |
| 30 | async function latency(func, iterations, argsFunc = () => []) { |
| 31 | const executionTimes = []; |
| 32 | |
| 33 | for (let i = 0; i < iterations; i++) { |
| 34 | const args = argsFunc(); |
| 35 | |
| 36 | const startTime = Date.now(); |
| 37 | let endTime; |
| 38 | |
| 39 | try { |
| 40 | await func(...args); |
| 41 | endTime = Date.now(); |
| 42 | } catch (e) { |
| 43 | endTime = Number.POSITIVE_INFINITY; |
| 44 | console.error(e); |
| 45 | continue; |
| 46 | } |
| 47 | |
| 48 | executionTimes.push(endTime - startTime); |
| 49 | } |
| 50 | |
| 51 | // Calculate statistics |
| 52 | const min = Math.min(...executionTimes); |
| 53 | const max = Math.max(...executionTimes); |
| 54 | const totalTime = executionTimes.reduce((sum, time) => sum + time, 0); |
| 55 | const average = totalTime / iterations; |
| 56 | |
| 57 | return { |
| 58 | min: min, |
| 59 | max: max, |
| 60 | average: average, |
| 61 | totalTime, |
| 62 | // times: executionTimes // Array of all execution times |
| 63 | }; |
| 64 | } |
| 65 | |
| 66 | async function benchmark() { |
| 67 | await hello_("world"); // Warmup |