react-native-benchmark
Version:
React Native benchmarking library inspired by benchmark.js
88 lines (87 loc) • 3.33 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Benchmark = void 0;
const events_1 = require("events");
const event_1 = require("./event");
const options_1 = require("./types/options");
const stats_1 = require("./types/stats");
const times_1 = require("./types/times");
const utils_1 = require("./utils");
const SECOND = 1000; // ms
class Benchmark extends events_1.EventEmitter {
constructor(name, fn, options) {
super();
this.id = '';
this.name = '';
this.count = 0;
this.cycles = 0;
this.running = false;
this.stats = new stats_1.Stats();
this.times = times_1.defaultTimes;
this.clone = () => {
const copy = new this.constructor();
Object.assign(copy, this);
return copy;
};
this.initRun = () => {
this.times.timeStamp = utils_1.now();
this.emit(event_1.EventType.START, new event_1.Event(event_1.EventType.START, this));
this.running = true;
const start = utils_1.now();
this.fn();
const end = utils_1.now();
const period = (end - start) / SECOND;
this.times.cycle = period;
this.times.period = period;
this.count = 1;
this.emit(event_1.EventType.CYCLE, new event_1.Event(event_1.EventType.CYCLE, this));
};
this.cycle = () => new Promise((resolve, _reject) => {
let flag = true;
const bench = this;
while (flag) {
const start = utils_1.now();
bench.fn();
const end = utils_1.now();
bench.count++;
bench.times.cycle = (end - start) / SECOND;
bench.emit(event_1.EventType.CYCLE, new event_1.Event(event_1.EventType.CYCLE, this));
if (utils_1.now() - bench.times.timeStamp > SECOND) {
flag = false;
const elapsed = (utils_1.now() - bench.times.timeStamp) / SECOND;
bench.times.elapsed = elapsed;
return resolve(bench.ops());
}
}
});
this.reset = () => {
this.times.timeStamp = utils_1.now();
this.times = times_1.defaultTimes;
this.count = 0;
};
this.run = async (options) => {
this.initRun();
let samplesCounter = options.minSamples;
while (samplesCounter--) {
const ops = await this.cycle();
this.stats.sample.push(ops);
this.reset();
}
this.complete();
};
this.complete = () => {
this.running = false;
this.emit(event_1.EventType.COMPLETE, new event_1.Event(event_1.EventType.COMPLETE, this));
};
this.ops = () => Math.floor(this.count / this.times.elapsed);
this.toString = () => `${this.name} - ${this.stats.mean.toFixed(0)} ops/sec \xb1 ${this.stats.rme.toFixed(2)}%`;
this.id = `${name}-${new Date().getTime()}`;
this.name = name;
this.fn = fn;
this.options = {
...options_1.defaultOptions,
...options
};
}
}
exports.Benchmark = Benchmark;