💾benchmark(f)

JStechniquedecorator💾 benchmark(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.

Last updated