How to measure the execution time of a promise?

If the functions you want to measure will always be synchronous there’s really no need to involve promises.

Since the function you want to test takes parameters you it’s best to to wrap it in an arrow function in order to be able to call it with another context and not have to manage it’s parameters yourself.

Something simple like this will do just fine.

function measure(fn: () => void): number {
    let start = performance.now();
    fn();
    return performance.now() - start;
}

function longRunningFunction(n: number) {
    for (let i = 0; i < n; i++) {
        console.log(i);
    }
}

let duration = measure(() => {
    longRunningFunction(100);
});

console.log(`took ${duration} ms`);

If you want to measure the time it takes an async function (if it returns a promise) to resolve you can easily change the code to something like this:

function measurePromise(fn: () => Promise<any>): Promise<number> {
    let onPromiseDone = () => performance.now() - start;

    let start = performance.now();
    return fn().then(onPromiseDone, onPromiseDone);
}

function longPromise(delay: number) {
    return new Promise<string>((resolve) => {
        setTimeout(() => {
            resolve('Done');
        }, delay);
    });
}

measurePromise(() => longPromise(300))
    .then((duration) => {
        console.log(`promise took ${duration} ms`);
    });

Note: This solution uses the ES6 Promise, if you are using something else you might have to adapt it but the logic should be the same.

You can see both examples working in the playground here.

Leave a Comment