astro/packages/astro/test/benchmark/benchmark.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

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';
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)) {
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) {
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`);
}
async save() {
const { file, name } = this.options;
2021-05-26 15:33:35 +00:00
const data = JSON.stringify(
{
name,
time: this.time,
},
null,
' '
);
await fsPromises.writeFile(file, data, 'utf-8');
}
async test() {
await this.run();
2021-05-26 15:33:35 +00:00
if (shouldSave) {
await this.save();
}
this.report();
this.check();
}
}