File size: 12,163 Bytes
30c32c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
388
389
390
391
/**
 * @fileoverview
 * A way to profile Scratch internal performance. Like what blocks run during a
 * step? How much time do they take? How much time is spent inbetween blocks?
 *
 * Profiler aims for to spend as little time inside its functions while
 * recording. For this it has a simple internal record structure that records a
 * series of values for each START and STOP event in a single array. This lets
 * all the values be pushed in one call for the array. This simplicity allows
 * the contents of the start() and stop() calls to be inlined in areas that are
 * called frequently enough to want even greater performance from Profiler so
 * what is recorded better reflects on the profiled code and not Profiler
 * itself.
 */

/**
 * The next id returned for a new profile'd function.
 * @type {number}
 */
let nextId = 0;

/**
 * The mapping of names to ids.
 * @const {Object.<string, number>}
 */
const profilerNames = {};

/**
 * The START event identifier in Profiler records.
 * @const {number}
 */
const START = 0;

/**
 * The STOP event identifier in Profiler records.
 * @const {number}
 */
const STOP = 1;

/**
 * The number of cells used in the records array by a START event.
 * @const {number}
 */
const START_SIZE = 4;

/**
 * The number of cells used in the records array by a STOP event.
 * @const {number}
 */
const STOP_SIZE = 2;

/**
 * Stored reference to Performance instance provided by the Browser.
 * @const {Performance}
 */
const performance = typeof window === 'object' && window.performance;


/**
 * Callback handle called by Profiler for each frame it decodes from its
 * records.
 * @callback FrameCallback
 * @param {ProfilerFrame} frame
 */

/**
 * A set of information about a frame of execution that was recorded.
 */
class ProfilerFrame {
    /**
     * @param {number} depth Depth of the frame in the recorded stack.
     */
    constructor (depth) {
        /**
         * The numeric id of a record symbol like Runtime._step or
         * blockFunction.
         * @type {number}
         */
        this.id = -1;

        /**
         * The amount of time spent inside the recorded frame and any deeper
         * frames.
         * @type {number}
         */
        this.totalTime = 0;

        /**
         * The amount of time spent only inside this record frame. Not
         * including time in any deeper frames.
         * @type {number}
         */
        this.selfTime = 0;

        /**
         * An arbitrary argument for the recorded frame. For example a block
         * function might record its opcode as an argument.
         * @type {*}
         */
        this.arg = null;

        /**
         * The depth of the recorded frame. This can help compare recursive
         * funtions that are recorded. Each level of recursion with have a
         * different depth value.
         * @type {number}
         */
        this.depth = depth;

        /**
         * A summarized count of the number of calls to this frame.
         * @type {number}
         */
        this.count = 0;
    }
}

class Profiler {
    /**
     * @param {FrameCallback} onFrame a handle called for each recorded frame.
     * The passed frame value may not be stored as it'll be updated with later
     * frame information. Any information that is further stored by the handler
     * should make copies or reduce the information.
     */
    constructor (onFrame = function () {}) {
        /**
         * A series of START and STOP values followed by arguments. After
         * recording is complete the full set of records is reported back by
         * stepping through the series to connect the relative START and STOP
         * information.
         * @type {Array.<*>}
         */
        this.records = [];

        /**
         * An array of frames incremented on demand instead as part of start
         * and stop.
         * @type {Array.<ProfilerFrame>}
         */
        this.increments = [];

        /**
         * An array of profiler frames separated by counter argument. Generally
         * for Scratch these frames are separated by block function opcode.
         * This tracks each time an opcode is called.
         * @type {Array.<ProfilerFrame>}
         */
        this.counters = [];

        /**
         * A frame with no id or argument.
         * @type {ProfilerFrame}
         */
        this.nullFrame = new ProfilerFrame(-1);

        /**
         * A cache of ProfilerFrames to reuse when reporting the recorded
         * frames in records.
         * @type {Array.<ProfilerFrame>}
         */
        this._stack = [new ProfilerFrame(0)];

        /**
         * A callback handle called with each decoded frame when reporting back
         * all the recorded times.
         * @type {FrameCallback}
         */
        this.onFrame = onFrame;

        /**
         * A reference to the START record id constant.
         * @const {number}
         */
        this.START = START;

        /**
         * A reference to the STOP record id constant.
         * @const {number}
         */
        this.STOP = STOP;
    }

    /**
     * Start recording a frame of time for an id and optional argument.
     * @param {number} id The id returned by idByName for a name symbol like
     * Runtime._step.
     * @param {?*} arg An arbitrary argument value to store with the frame.
     */
    start (id, arg) {
        this.records.push(START, id, arg, performance.now());
    }

    /**
     * Stop the current frame.
     */
    stop () {
        this.records.push(STOP, performance.now());
    }

    /**
     * Increment the number of times this symbol is called.
     * @param {number} id The id returned by idByName for a name symbol.
     */
    increment (id) {
        if (!this.increments[id]) {
            this.increments[id] = new ProfilerFrame(-1);
            this.increments[id].id = id;
        }
        this.increments[id].count += 1;
    }

    /**
     * Find or create a ProfilerFrame-like object whose counter can be
     * incremented outside of the Profiler.
     * @param {number} id The id returned by idByName for a name symbol.
     * @param {*} arg The argument for a frame that identifies it in addition
     *   to the id.
     * @return {{count: number}} A ProfilerFrame-like whose count should be
     *   incremented for each call.
     */
    frame (id, arg) {
        for (let i = 0; i < this.counters.length; i++) {
            if (this.counters[i].id === id && this.counters[i].arg === arg) {
                return this.counters[i];
            }
        }

        const newCounter = new ProfilerFrame(-1);
        newCounter.id = id;
        newCounter.arg = arg;
        this.counters.push(newCounter);
        return newCounter;
    }

    /**
     * Decode records and report all frames to `this.onFrame`.
     */
    reportFrames () {
        const stack = this._stack;
        let depth = 1;

        // Step through the records and initialize Frame instances from the
        // START and STOP events. START and STOP events are separated by events
        // for deeper frames run by higher frames. Frames are stored on a stack
        // and reinitialized for each START event. When a stop event is reach
        // the Frame for the current depth has its final values stored and its
        // passed to the current onFrame callback. This way Frames are "pushed"
        // for each START event and "popped" for each STOP and handed to an
        // outside handle to any desired reduction of the collected data.
        for (let i = 0; i < this.records.length;) {
            if (this.records[i] === START) {
                if (depth >= stack.length) {
                    stack.push(new ProfilerFrame(depth));
                }

                // Store id, arg, totalTime, and initialize selfTime.
                const frame = stack[depth++];
                frame.id = this.records[i + 1];
                frame.arg = this.records[i + 2];
                // totalTime is first set as the time recorded by this START
                // event. Once the STOP event is reached the stored start time
                // is subtracted from the recorded stop time. The resulting
                // difference is the actual totalTime, and replaces the start
                // time in frame.totalTime.
                //
                // totalTime is used this way as a convenient member to store a
                // value between the two events without needing additional
                // members on the Frame or in a shadow map.
                frame.totalTime = this.records[i + 3];
                // selfTime is decremented until we reach the STOP event for
                // this frame. totalTime will be added to it then to get the
                // time difference.
                frame.selfTime = 0;

                i += START_SIZE;
            } else if (this.records[i] === STOP) {
                const now = this.records[i + 1];

                const frame = stack[--depth];
                // totalTime is the difference between the start event time
                // stored in totalTime and the stop event time pulled from this
                // record.
                frame.totalTime = now - frame.totalTime;
                // selfTime is the difference of this frame's totalTime and the
                // sum of totalTime of deeper frames.
                frame.selfTime += frame.totalTime;

                // Remove this frames totalTime from the parent's selfTime.
                stack[depth - 1].selfTime -= frame.totalTime;

                // This frame occured once.
                frame.count = 1;

                this.onFrame(frame);

                i += STOP_SIZE;
            } else {
                this.records.length = 0;
                throw new Error('Unable to decode Profiler records.');
            }
        }

        for (let j = 0; j < this.increments.length; j++) {
            if (this.increments[j] && this.increments[j].count > 0) {
                this.onFrame(this.increments[j]);
                this.increments[j].count = 0;
            }
        }

        for (let k = 0; k < this.counters.length; k++) {
            if (this.counters[k].count > 0) {
                this.onFrame(this.counters[k]);
                this.counters[k].count = 0;
            }
        }

        this.records.length = 0;
    }

    /**
     * Lookup or create an id for a frame name.
     * @param {string} name The name to return an id for.
     * @return {number} The id for the passed name.
     */
    idByName (name) {
        return Profiler.idByName(name);
    }

    /**
     * Reverse lookup the name from a given frame id.
     * @param {number} id The id to search for.
     * @return {string} The name for the given id.
     */
    nameById (id) {
        return Profiler.nameById(id);
    }

    /**
     * Lookup or create an id for a frame name.
     * @static
     * @param {string} name The name to return an id for.
     * @return {number} The id for the passed name.
     */
    static idByName (name) {
        if (typeof profilerNames[name] !== 'number') {
            profilerNames[name] = nextId++;
        }
        return profilerNames[name];
    }

    /**
     * Reverse lookup the name from a given frame id.
     * @static
     * @param {number} id The id to search for.
     * @return {string} The name for the given id.
     */
    static nameById (id) {
        for (const name in profilerNames) {
            if (profilerNames[name] === id) {
                return name;
            }
        }
        return null;
    }

    /**
     * Profiler is only available on platforms with the Performance API.
     * @return {boolean} Can the Profiler run in this browser?
     */
    static available () {
        return (
            typeof window === 'object' &&
            typeof window.performance !== 'undefined');
    }
}


/**
 * A reference to the START record id constant.
 * @const {number}
 */
Profiler.START = START;

/**
 * A reference to the STOP record id constant.
 * @const {number}
 */
Profiler.STOP = STOP;

module.exports = Profiler;