-
Notifications
You must be signed in to change notification settings - Fork 3
/
benchmark.js
92 lines (78 loc) · 1.91 KB
/
benchmark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const Table = require('cli-table');
function benchmark(callback) {
this.befores = [];
this.beforeEachs = [];
this.runs = [];
this.table = new Table({
head: ['Description', 'Consumed Gas'],
colWidths: [100, 15],
});
callback.call(this);
execute.call(this);
}
async function execute() {
// befores
const befores = this.befores;
for (let i = 0; i < befores.length; i++) {
try {
// eslint-disable-next-line no-await-in-loop
await befores[i]();
} catch (e) {
console.log('Error:', e);
process.exit(1);
return;
}
}
// runs
const runs = this.runs;
for (let i = 0; i < runs.length; i++) {
const run = runs[i];
if (run.type === 'title') {
this.table.push([run.name, '']);
continue;
}
// before Eachs
{
for (let i = 0; i < this.beforeEachs.length; i++) {
try {
await this.beforeEachs[i]()
} catch (e) {
console.log('Error:', e);
process.exit(1);
return;
}
}
}
try {
let res = await run.callback();
let gas = (typeof res === 'object' && 'receipt' in res) ? (res.receipt.gasUsed - 21000) : res;
this.table.push([run.name, gas.toLocaleString('en')])
// console.log(`${run.name}: ${res.receipt.gasUsed} gas`);
} catch (e) {
console.log('Benchmark Error:', e);
process.exit(1);
return;
}
}
console.log(this.table.toString());
process.exit(0);
}
function describe(name, callback) {
this.runs.push({ type: 'title', name });
callback.call(this);
}
function run(name, callback) {
this.runs.push({ name, callback });
return { name, callback };
}
function before(callback) {
this.befores.push(callback);
}
function beforeEach(callback) {
this.beforeEachs.push(callback);
}
global.run = run;
global.before = before;
global.beforeEach = beforeEach;
global.describe = describe;
module.exports = benchmark;