UNPKG

kruonis

Version:
108 lines (107 loc) 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Test = void 0; const internal_1 = require("./internal"); const now = require("performance-now"); /** * A test represents a code that shall be run and afterwards compared regarding the performance */ class Test { /** * @param name The test name * @param fn The function to be run */ constructor(name, fn) { this.name = name; this.fn = fn; /** * The measured times for the ran cycles, in milliseconds */ this.cycleTimes = []; /** * The stats obtained by running this test */ this.stats = null; /** * Function to run on the begin of the test */ this.onBegin = (test) => { }; /** * Function to run after before running each cycle */ this.onCycleBegin = (test) => { }; /** * Function to run after each cycle completes */ this.onCycleEnd = (test) => { }; /** * Function to run on the end of all test cycles */ this.onEnd = (test) => { }; } /** * Add an event to this Test. Possibilities: * - 'onBegin' * - 'onCycleBegin' * - 'onCycleEnd' * - 'onEnd' * * @param eventName The name of the event to be altered * @param fn The function that will run when the event is called */ on(eventName, fn) { if (eventName.substr(0, 2) == "on" && this.hasOwnProperty(eventName)) this[eventName] = fn; return this; } /** * Gets the test baseline time (the time it takes to measure the times) */ getBaselineTime() { const startTime = now(); const endTime = now(); return endTime - startTime; } /** * Run this test according to the given testProperties * * @param testProperties the testProperties to use on this test. Similar to a @BenchmarkProperties object */ run(testProperties) { // Times are measured in milliseconds let totalTime = 0; const { minCycles, maxCycles, maxTime } = testProperties; const maxTimeMS = maxTime * Test.SECONDS_TO_MILLISECONDS; const baselineTime = this.getBaselineTime(); this.onBegin(this); while (this.cycleTimes.length < minCycles || (totalTime < maxTimeMS && this.cycleTimes.length < maxCycles)) { this.onCycleBegin(this); // Measure performance const startTime = now(); this.fn(); const endTime = now(); // Remove baseline times from performance testing let testTime = (endTime - startTime - baselineTime); // Because of small deviations testTime = testTime < 0 ? 0 : testTime; // Save times this.cycleTimes.push(testTime); totalTime += testTime; this.onCycleEnd(this); } this.stats = new internal_1.Stats(this.cycleTimes); this.onEnd(this); } ; /** * Get the stats obtained by running this test * * @return @Stats instance */ getStats() { return this.stats; } } exports.Test = Test; Test.SECONDS_TO_MILLISECONDS = 1000;