Last updated 1 year ago
JS ⟩ technique ⟩ decorator ⟩ benchmark(f)
(decorator)
replit:timed(f)
// ⭐ benchmark a function function benchmark(f) { return function(...args) { console.log(`• Entering function: ${f.name}(${args}) ...`); let startTime = Date.now(); try { return f.apply(this, args); // forward call } finally { const s = (Date.now() - startTime) / 1000; console.log(`• Exiting ${f.name} after ${s} sec.`); } }; }
example
// test function function addFrom1To(n) { let sum = 0; for (let i = 1; i <= n; i++) sum += i; return sum; } benchmark(addFrom1To)(1000000) // 500000500000 // • Entering function: addFrom1To(1000000) ... // • Exiting addFrom1To after 0.023 sec.
JavaScript: The Definitive Guide > 8.3.4 The Spread Operator for Function Calls
measureTime()