如何衡量承诺的执行时间? [英] How to measure the execution time of a promise?

查看:127
本文介绍了如何衡量承诺的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测量另一个函数执行时间的函数:

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

export class Profiler {
    public measureSyncFunc(fn: () => any): Promise<number> {
        return new Promise<number>((resolve, reject) => {
            let elapsed = 0;

            let intervalId = window.setInterval(() => {
                elapsed += 1; // this is never called
            }, 1);

            this.execFunc(fn)
                .then((result: any) => {
                    window.clearInterval(intervalId);
                    resolve(elapsed);
                });
        });
    }

    private execFunc(fn: () => any): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            resolve(fn());
        });
    }
}

然后我就这样使用它:

let array = generateRandomArray(100000);

instance.measureSyncFunc(bubbleSort(array))
    .then((elapsed: number) => {
        console.log(`end session: ${elapsed} seconds`);
        resolve();
    });

bubbleSort函数是同步的,需要几秒钟才能完成。
请参阅代码此处

The bubbleSort function is synchronous and it takes several seconds to complete. See code here:

控制台中的结果是结束会话:0秒,因为永远不会调用间隔回调。

The result in the console is "end session: 0 seconds" because the interval callback is never called.

你知道如何调用它吗?
非常感谢你们!

Do you know how I can make it called ? Thank you very much guys !

推荐答案

如果您要测量的功能始终是同步的,那么真的没有必要涉及承诺。

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`);

如果要测量异步功能所需的时间(如果它返回一个promise来解决你可以轻松地将代码更改为这样的代码:

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`);
    });

注意:此解决方案使用ES6 承诺,如果你正在使用其他东西,你可能需要调整它,但逻辑应该是相同的。

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.

这篇关于如何衡量承诺的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆