How to measure the execution time of a promise?

前端 未结 4 1849
迷失自我
迷失自我 2020-12-03 15:05

I\'m trying to write a function that measures the execution time of another function:

export class Profiler {
    public measureSyncFunc(fn: () => any): P         


        
4条回答
  •  旧巷少年郎
    2020-12-03 15:46

    Don't use setInterval to count milliseconds (It's inaccurate, lags, drifts and has a minimum interval of about 4ms). Just get two timestamps before and after the execution.

    function measureASyncFunc(fn: () => Promise): Promise {
        const start = Date.now();
        return fn.catch(() => {}).then(() => {
            const end = Date.now();
            const elapsed = end-start;
            return elapsed;
        });
    }
    

    For higher accuracy, replace Date.now by performance.now.

提交回复
热议问题