1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function alignLeft(str, len, ch) {
|
22 | return str + new Array(len - str.length + 1).join(ch || " ");
|
23 | }
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | function alignRight(str, len, ch) {
|
35 | return new Array(len - str.length + 1).join(ch || " ") + str;
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | const enabled = !!process.env.TIMING;
|
43 |
|
44 | const HEADERS = ["Rule", "Time (ms)", "Relative"];
|
45 | const ALIGN = [alignLeft, alignRight, alignRight];
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | function display(data) {
|
55 | let total = 0;
|
56 | const rows = Object.keys(data)
|
57 | .map(function(key) {
|
58 | const time = data[key];
|
59 |
|
60 | total += time;
|
61 | return [key, time];
|
62 | })
|
63 | .sort(function(a, b) {
|
64 | return b[1] - a[1];
|
65 | })
|
66 | .slice(0, 10);
|
67 |
|
68 | rows.forEach(function(row) {
|
69 | row.push((row[1] * 100 / total).toFixed(1) + "%");
|
70 | row[1] = row[1].toFixed(3);
|
71 | });
|
72 |
|
73 | rows.unshift(HEADERS);
|
74 |
|
75 | const widths = [];
|
76 |
|
77 | rows.forEach(function(row) {
|
78 | const len = row.length;
|
79 |
|
80 | for (let i = 0; i < len; i++) {
|
81 | const n = row[i].length;
|
82 |
|
83 | if (!widths[i] || n > widths[i]) {
|
84 | widths[i] = n;
|
85 | }
|
86 | }
|
87 | });
|
88 |
|
89 | const table = rows.map(function(row) {
|
90 | return row.map(function(cell, index) {
|
91 | return ALIGN[index](cell, widths[index]);
|
92 | }).join(" | ");
|
93 | });
|
94 |
|
95 | table.splice(1, 0, widths.map(function(w, index) {
|
96 | if (index !== 0 && index !== widths.length - 1) {
|
97 | w++;
|
98 | }
|
99 |
|
100 | return ALIGN[index](":", w + 1, "-");
|
101 | }).join("|"));
|
102 |
|
103 | console.log(table.join("\n"));
|
104 | }
|
105 |
|
106 |
|
107 | module.exports = (function() {
|
108 |
|
109 | const data = Object.create(null);
|
110 |
|
111 | |
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 | function time(key, fn) {
|
119 | if (typeof data[key] === "undefined") {
|
120 | data[key] = 0;
|
121 | }
|
122 |
|
123 | return function() {
|
124 | let t = process.hrtime();
|
125 |
|
126 | fn.apply(null, Array.prototype.slice.call(arguments));
|
127 | t = process.hrtime(t);
|
128 | data[key] += t[0] * 1e3 + t[1] / 1e6;
|
129 | };
|
130 | }
|
131 |
|
132 | if (enabled) {
|
133 | process.on("exit", function() {
|
134 | display(data);
|
135 | });
|
136 | }
|
137 |
|
138 | return {
|
139 | time,
|
140 | enabled
|
141 | };
|
142 |
|
143 | }());
|