2021-05-26 15:31:53 +00:00
|
|
|
import { promises as fsPromises, existsSync } from 'fs';
|
|
|
|
import { performance } from 'perf_hooks';
|
2021-09-16 20:06:43 +00:00
|
|
|
import * as assert from 'uvu/assert';
|
2021-05-26 15:31:53 +00:00
|
|
|
|
|
|
|
const MUST_BE_AT_LEAST_PERC_OF = 90;
|
|
|
|
|
|
|
|
const shouldSave = process.argv.includes('--save');
|
|
|
|
|
|
|
|
export class Benchmark {
|
|
|
|
constructor(options) {
|
|
|
|
this.options = options;
|
|
|
|
this.setup = options.setup || Function.prototype;
|
|
|
|
}
|
|
|
|
|
|
|
|
async execute() {
|
|
|
|
const { run } = this.options;
|
|
|
|
const start = performance.now();
|
|
|
|
const end = await run(this.options);
|
|
|
|
const time = Math.floor(end - start);
|
|
|
|
return time;
|
|
|
|
}
|
|
|
|
|
|
|
|
async run() {
|
|
|
|
const { file } = this.options;
|
|
|
|
|
|
|
|
await this.setup();
|
|
|
|
const time = await this.execute();
|
2021-05-26 15:33:35 +00:00
|
|
|
|
|
|
|
if (existsSync(file)) {
|
2021-05-26 15:31:53 +00:00
|
|
|
const raw = await fsPromises.readFile(file, 'utf-8');
|
|
|
|
const data = JSON.parse(raw);
|
2021-05-26 15:33:35 +00:00
|
|
|
if (Math.floor((data.time / time) * 100) > MUST_BE_AT_LEAST_PERC_OF) {
|
2021-05-26 15:31:53 +00:00
|
|
|
this.withinPreviousRuns = true;
|
|
|
|
} else {
|
|
|
|
this.withinPreviousRuns = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this.time = time;
|
|
|
|
}
|
|
|
|
|
|
|
|
report() {
|
|
|
|
const { name } = this.options;
|
|
|
|
console.log(name, 'took', this.time, 'ms');
|
|
|
|
}
|
|
|
|
|
|
|
|
check() {
|
2021-07-20 19:22:29 +00:00
|
|
|
assert.ok(this.withinPreviousRuns !== false, `${this.options.name} ran too slowly`);
|
2021-05-26 15:31:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async save() {
|
|
|
|
const { file, name } = this.options;
|
2021-05-26 15:33:35 +00:00
|
|
|
const data = JSON.stringify(
|
|
|
|
{
|
|
|
|
name,
|
|
|
|
time: this.time,
|
|
|
|
},
|
|
|
|
null,
|
|
|
|
' '
|
|
|
|
);
|
2021-05-26 15:31:53 +00:00
|
|
|
await fsPromises.writeFile(file, data, 'utf-8');
|
|
|
|
}
|
|
|
|
|
|
|
|
async test() {
|
|
|
|
await this.run();
|
2021-05-26 15:33:35 +00:00
|
|
|
if (shouldSave) {
|
2021-05-26 15:31:53 +00:00
|
|
|
await this.save();
|
|
|
|
}
|
|
|
|
this.report();
|
|
|
|
this.check();
|
|
|
|
}
|
|
|
|
}
|