Как измерить время нескольких вызовов функции asyn c - PullRequest
1 голос
/ 27 мая 2020

У меня проблема с пониманием того, как работают функции asyn c в js. Поэтому мне нужно вызывать функцию asyn c 5 раз и измерять продолжительность каждого выполнения. В итоге у меня должен получиться массив с 5 значениями времени. У меня есть что-то вроде этого

for (let i = 0; i < 5; i++) {
    const run = async () => {
    await test(thisTest, filename, unitTestDict);
    };
    measure(run).then(report => {
                        // inspect
                        const {tSyncOnly, tSyncAsync} = report;
                        // array.push(tSyncAsync) 
                        console.log(`∑ = ${tSyncAsync}ms \t`);
                    }).catch(e => {
                        console.error(e)
                    });
}

Вот Я нашел реализацию функции измерения времени:


class Stack {
    constructor() {
        this._array = []
    }

    push(x) {
        return this._array.push(x)
    }

    peek() {
        return this._array[this._array.length - 1]
    }

    pop() {
        return this._array.pop()
    }

    get is_not_empty() {
        return this._array.length > 0
    }
}

class Timer {
    constructor() {
        this._records = new Map
        /* of {start:number, end:number} */
    }

    starts(scope) {
        const detail =
            this._records.set(scope, {
                start: this.timestamp(),
                end: -1,
            })
    }

    ends(scope) {
        this._records.get(scope).end = this.timestamp()
    }

    timestamp() {
        return performance.now()
    }

    timediff(t0, t1) {
        return Math.abs(t0 - t1)
    }

    report(scopes, detail) {
        let tSyncOnly = 0;
        let tSyncAsync = 0;
        for (const [scope, {start, end}] of this._records)
            if (scopes.has(scope))
                if (~end) {
                    tSyncOnly += end - start;
                    tSyncAsync += end - start;
                    const {type, offset} = detail.get(scope);
                    if (type === "Timeout")
                        tSyncAsync += offset;
                }
        return {tSyncOnly, tSyncAsync}
    }
}

async function measure(asyncFn) {
    const stack = new Stack;
    const scopes = new Set;
    const timer = new Timer;
    const detail = new Map;
    const hook = createHook({
        init(scope, type, parent, resource) {
            if (type === 'TIMERWRAP') return;
            scopes.add(scope);
            detail.set(scope, {
                type: type,
                offset: type === 'Timeout' ? resource._idleTimeout : 0
            })
        },
        before(scope) {
            if (stack.is_not_empty) timer.ends(stack.peek());
            stack.push(scope);
            timer.starts(scope)
        },
        after() {
            timer.ends(stack.pop())
        }
    });
    return await new Promise(r => {
        hook.enable();
        setTimeout(() => {
            asyncFn()
                .then(() => hook.disable())
                .then(() => r(timer.report(scopes, detail)))
                .catch(console.error)
        }, 1)
    })
}

Я могу вызвать это внутри l oop и получить console.log со временем для каждой итерации:

measure(run).then(report => {
                        // inspect
                        const {tSyncOnly, tSyncAsync} = report;
                        // array.push(tSyncAsync) 
                        console.log(`∑ = ${tSyncAsync}ms \t`);
                    }).catch(e => {
                        console.error(e)
                    });

Но когда я пытаюсь передать sh эти консольные значения в массив, ничего не выходит, массив остается пустым. Есть ли способ его заполнить?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...