forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile.js
388 lines (347 loc) · 9.6 KB
/
profile.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Tiny profiler
//
// Enable by setting the environment variable `METEOR_PROFILE`.
//
// The main entry point is `Profile`, which wraps an existing function
// and returns a new function which, when called, calls the original
// function and profiles it.
//
// before:
//
// foo: function (a) {
// return a + this.b;
// },
//
// after:
//
// foo: Profile("foo", function (a) {
// return a + this.b;
// }),
//
// The advantage of this form is that it doesn't change the
// indentation of the wrapped code, which makes merging changes from
// other code branches easier.
//
// If profiling is disabled (if `METEOR_PROFILE` isn't set), `Profile`
// simply returns the original function.
//
// To run a profiling session and print the report, call `Profile.run`:
//
// var createBundle = function () {
// Profile.run("bundle", function () {
// ...code to create the bundle which includes calls to `Profile`.
// });
// };
//
// Code is not profiled when called outside of a `Profile.run`, so the
// times in the report only include the time spent inside of the call
// to `Profile.run`.
//
// Sometimes you'll want to use a name for the profile bucket which
// depends on the arguments passed to the function or the value of
// `this`. In this case you can pass a function for the bucket
// argument, which will be called to get the bucket name.
//
// before:
// build: function (target) {
// ... build target ...
// },
//
// after:
// build: Profile(
// function (target) { return "build " + target; },
// function (target) {
// ... build target ...
// }),
//
// But if it's easier, you can use `Profile.time` instead, which
// immediately calls the passed function with no arguments and
// profiles it, and returns what the function returns.
//
// foo: function (a) {
// var self = this;
// return Profile.time("foo", function () {
// return a + self.b;
// });
// },
//
// build: function (target) {
// var self = this;
// self.doSomeSetup();
// Profile.time("build " + target, function () {
// ... build target ...
// });
// self.doSomeCleanup();
// },
//
// The disadvantage is that you end up changing the indentation of the
// profiled code, which makes merging branches more painful. But you
// can profile anywhere in the code; you don't have to just profile at
// function boundaries.
//
// Note profiling code will itself add a bit of execution time.
// If you profile in a tight loop and your total execution time is
// going up, you're probably starting to profile how long it takes to
// profile things :).
//
// If another profile (such as "compile js") is called while the first
// function is currently being profiled, this creates an entry like
// this:
//
// build client : compile js
//
// which can continue to be nested, e.g.,
//
// build client : compile js : read source files
//
// The total time reported for a bucket such as "build client" doesn't
// change regardless of whether it has child entries or not. However,
// if an entry has child entries, it automatically gets an "other"
// entry:
//
// build client: 400.0
// compile js: 300.0
// read source files: 20.0
// other compile js: 280.0
// other build client: 100.0
//
// The "other" entry reports how much time was spent in the "build
// client" entry not spent in the other child entries.
//
// The are two reports displayed: the hierarchical report and the
// leaf time report. The hierarchical report looks like the example
// above and shows how much time was spent in each entry within its
// parent entry.
//
// The primary purpose of the hierarchical report is to be able to see
// where times are unaccounted for. If you see a lot of time being
// spent in an "other" bucket, and you don't know what it is, you can
// add more profiling to dig deeper.
//
// The leaf time report shows the total time spent within leaf
// buckets. For example, if if multiple steps have "read source
// files", the leaf time reports shows the total amount of time spent
// in "read source files" across all calls.
//
// Once you see in the hierarchical report that you have a good handle
// on accounting for most of the time, the leaf report shows you which
// buckets are the most expensive.
//
// By only including leaf buckets, the times in the leaf report are
// non-overlapping. (The total of the times equals the elapsed time
// being profiled).
//
// For example, suppose "A" is profiled for a total time of 200ms, and
// that includes a call to "B" of 150ms:
//
// B: 150
// A (without B): 50
//
// and suppose there's another call to "A" which *doesn't* include a
// call to "B":
//
// A: 300
//
// and there's a call to "B" directly:
//
// B: 100
//
// All for a total time of 600ms. In the hierarchical report, this
// looks like:
//
// A: 500.0
// B: 150.0
// other A: 350.0
// B: 100.0
//
// and in the leaf time report:
//
// other A: 350.0
// B: 250.0
//
// In both reports the grand total is 600ms.
var _ = require('underscore');
var Fiber = require('fibers');
var enabled = !! process.env['METEOR_PROFILE'];
var bucketTimes = {};
var spaces = function (x) {
var s = '';
for (var i = 0; i < x; ++i)
s += ' ';
return s;
};
var globalEntry = [];
var running = false;
var start = function () {
bucketTimes = {};
running = true;
};
var Profile = function (bucketName, f) {
if (! enabled)
return f;
return function (/*arguments*/) {
if (! running)
return f.apply(this, arguments);
var name;
if (_.isFunction(bucketName))
name = bucketName.apply(this, arguments);
else
name = bucketName;
var currentEntry;
if (Fiber.current) {
currentEntry =
Fiber.current.profilerEntry || (Fiber.current.profilerEntry = []);
} else {
currentEntry = globalEntry;
}
currentEntry.push(name);
var key = JSON.stringify(currentEntry);
var start = process.hrtime();
var err = null;
try {
return f.apply(this, arguments);
}
catch (e) {
err = e;
}
finally {
var elapsed = process.hrtime(start);
bucketTimes[key] = (bucketTimes[key] || 0) +
(elapsed[0] * 1000 + elapsed[1] / 1000000);
currentEntry.pop();
}
if (err) throw err;
};
};
var time = function (bucket, f) {
return Profile(bucket, f)();
};
var entries = null;
var prefix = "| ";
var entryName = function (entry) {
return _.last(entry);
};
var entryTime = function (entry) {
return bucketTimes[JSON.stringify(entry)];
};
var isTopLevelEntry = function (entry) {
return entry.length === 1;
};
var topLevelEntries = function () {
return _.filter(entries, isTopLevelEntry);
};
var print = function (indent, text) {
console.log(prefix + spaces(indent * 2) + text);
};
var startsWith = function (s1, s2) {
return (s1.substr(0, s2.length) === s2);
};
var isChild = function (entry1, entry2) {
return (entry2.length === entry1.length + 1 &&
_.isEqual(entry1, entry2.slice(0, entry1.length)));
};
var children = function (entry1) {
return _.filter(entries, function (entry2) {
return isChild(entry1, entry2);
});
}
var hasChildren = function (entry) {
return children(entry).length !== 0;
};
var isLeaf = function (entry) {
return ! hasChildren(entry);
};
var reportOnLeaf = function (level, entry) {
print(
level,
_.last(entry) + ": " + entryTime(entry).toFixed(1));
};
var otherTime = function (entry) {
var total = 0;
_.each(children(entry), function (child) {
total += bucketTimes[JSON.stringify(child)];
});
return entryTime(entry) - total;
};
var injectOtherTime = function (entry) {
var name = "other " + entryName(entry);
var other = _.clone(entry);
other.push(name);
bucketTimes[JSON.stringify(other)] = otherTime(entry);
entries.push(other);
};
var reportOnParent = function (level, entry) {
print(level, entryName(entry) + ": " + entryTime(entry).toFixed(1));
_.each(children(entry), function (child) {
reportOn(level + 1, child);
});
};
var reportOn = function (level, entry) {
if (hasChildren(entry))
reportOnParent(level, entry);
else
reportOnLeaf(level, entry);
};
var reportHierarchy = function () {
_.each(topLevelEntries(), function (entry) {
reportOn(0, entry);
});
};
var allLeafs = function () {
return _.union(_.map(_.filter(entries, isLeaf), entryName));
};
var leafTotal = function (leafName) {
var total = 0;
_.each(
_.filter(entries, function (entry) {
return isLeaf(entry) && entryName(entry) === leafName;
}),
function (leaf) {
total += entryTime(leaf);
}
);
return total;
};
var reportTotals = function () {
var totals = [];
_.each(allLeafs(), function (leaf) {
totals.push({name: leaf, time: leafTotal(leaf)});
});
totals.sort(function (a, b) {
return a.time === b.time ? 0 : a.time > b.time ? -1 : 1;
});
var grandTotal = 0;
_.each(totals, function (total) {
print(0, total.name + ": " + total.time.toFixed(1));
grandTotal += total.time;
});
print(0, "Total: " + grandTotal.toFixed(1));
};
var setupReport = function () {
entries = _.map(_.keys(bucketTimes), JSON.parse);
_.each(_.filter(entries, hasChildren), function (parent) {
injectOtherTime(parent);
});
};
var report = function () {
if (! enabled)
return;
running = false;
print(0, '');
setupReport();
reportHierarchy();
print(0, '');
reportTotals();
};
var run = function (bucketName, f) {
start();
try {
return time(bucketName, f);
}
finally {
report();
}
};
Profile.time = time;
Profile.run = run;
exports.Profile = Profile;