UNPKG

1.29 kBJavaScriptView Raw
1export function createNoopProfiler() {
2 return {
3 run(fn) {
4 return Promise.resolve().then(() => fn());
5 },
6 collect() {
7 return [];
8 },
9 };
10}
11export function createProfiler() {
12 const events = [];
13 return {
14 collect() {
15 return events;
16 },
17 run(fn, name, cat) {
18 let startTime;
19 return Promise.resolve()
20 .then(() => {
21 startTime = process.hrtime();
22 })
23 .then(() => fn())
24 .then(value => {
25 const duration = process.hrtime(startTime);
26 // Trace Event Format documentation:
27 // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
28 const event = {
29 name,
30 cat,
31 ph: 'X',
32 ts: hrtimeToMicroseconds(startTime),
33 pid: 1,
34 tid: 0,
35 dur: hrtimeToMicroseconds(duration),
36 };
37 events.push(event);
38 return value;
39 });
40 },
41 };
42}
43function hrtimeToMicroseconds(hrtime) {
44 return (hrtime[0] * 1e9 + hrtime[1]) / 1000;
45}