forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time-code.js
61 lines (54 loc) · 1.88 KB
/
time-code.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import { sendAnalytics } from './analytics';
const MAX_TIMINGS_PER_LABEL = 3;
const _timingsPerLabel = {};
let _performanceMeasureGeneration = 0;
/**
* We care about timing information. This function helps log and collect information
* about how fast our functions are.
*/
export function timeCode<T>(label: string, codeAsACallback: () => T): T {
if (typeof performance !== 'undefined') {
let markName;
if (process.env.NODE_ENV === 'development') {
if (performance.mark) {
markName = `time-code-${_performanceMeasureGeneration++}`;
performance.mark(markName);
}
}
const start = performance.now();
const result = codeAsACallback();
const elapsed = Math.round(performance.now() - start);
// Only log timing information in development mode.
if (process.env.NODE_ENV === 'development') {
// Record a UserTiming for this timeCode call.
if (performance.measure) {
performance.measure(`TimeCode: ${label}`, markName);
}
const style = 'font-weight: bold; color: #f0a';
console.log(
`[timing] %c"${label}"`,
style,
`took ${elapsed}ms to execute.`
);
}
// Some portion of users will have timing information sent. Limit this further to
// only send a few labels per user.
const sentTimings = _timingsPerLabel[label] || 0;
if (sentTimings < MAX_TIMINGS_PER_LABEL) {
_timingsPerLabel[label] = 1 + sentTimings;
sendAnalytics({
hitType: 'timing',
timingCategory: 'timeCode',
timingVar: label,
timingValue: elapsed,
});
}
// Return the actual result.
return result;
}
return codeAsACallback();
}