-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (58 loc) · 1.62 KB
/
index.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
module.exports.timer = (() => {
let _timers = {};
let _records = {};
const _timer = (label = '_init', reset) => {
if (!_timers[label] && !reset) {
_timers[label] = process.hrtime();
return;
}
if (reset) {
delete _timers[label];
_records[label] = [];
_timers[label] = process.hrtime();
}
const hrtime = process.hrtime(_timers[label]);
return Number((hrtime[0] + (hrtime[1] * 1e-9)).toPrecision(16));
};
const prettyPrint = (label, seconds) => {
if (seconds < 1e-6) return label + ': ' + (seconds * 1e9) + ' ns';
if (seconds < 1) return label + ': ' + (seconds * 1e3) + ' ms';
return label + ': ' + seconds + ' s';
};
_timer.reset = () => {
_timers = {};
_labels = {};
}
_timer.start = (label) => _timer(label, true);
_timer.end = (label) => {
const seconds = _timer(label);
_records[label] = _records[label] || [];
_records[label].push(seconds);
return seconds;
};
_timer.log = (label = "") => {
if (!label) {
console.log(_records);
Object.keys(_records)
.forEach(key => {
console.log(
prettyPrint(key, _records[key]
.reduce((a, b) => a + b, 0) / _records[key].length
)
);
});
return;
}
const seconds = _timer(label);
console.log(prettyPrint(label, seconds));
};
_timer.results = () => {
return Object.keys(_records)
.reduce((output, label) => {
output[label] = _records[label]
.reduce((a, b) => a + b, 0) / _records[label].length;
return output;
}, {});
}
return _timer;
})();