forked from node-inspector/v8-profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
v8-profiler.js
107 lines (82 loc) · 2.51 KB
/
v8-profiler.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
var binding = require('./build/Release/profiler.node');
var Stream = require('stream').Stream;
function CpuProfile() {}
CpuProfile.prototype.getHeader = function() {
return {
typeId: this.typeId,
uid: this.uid,
title: this.title
}
}
CpuProfile.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();
var toStream = dataReceiver instanceof Stream;
var error, result;
try {
result = JSON.stringify(this);
} catch (err) {
error = err;
}
process.nextTick(function() {
if (toStream) {
if (error) {
dataReceiver.emit('error', error);
}
dataReceiver.end(result);
} else {
dataReceiver(error, result);
}
});
return toStream ? dataReceiver : undefined;
};
var startTime, endTime;
var activeProfiles = [];
var profiler = {
/*CPU PROFILER API*/
get profiles() { return binding.cpu.profiles; },
startProfiling: function(name, recsamples) {
if (activeProfiles.length == 0 && typeof process._startProfilerIdleNotifier == "function")
process._startProfilerIdleNotifier();
if (typeof name == 'boolean') {
recsamples = name;
name = '';
}
recsamples = recsamples === undefined ? true : Boolean(recsamples);
name = '' + name;
if (activeProfiles.indexOf(name) < 0)
activeProfiles.push(name)
startTime = Date.now();
binding.cpu.startProfiling(name, recsamples);
},
stopProfiling: function(name) {
var index = activeProfiles.indexOf(name);
if (name && index < 0)
return;
var profile = binding.cpu.stopProfiling(name);
endTime = Date.now();
profile.__proto__ = CpuProfile.prototype;
if (!profile.startTime) profile.startTime = startTime;
if (!profile.endTime) profile.endTime = endTime;
if (name)
activeProfiles.splice(index, 1);
else
activeProfiles.length = activeProfiles.length - 1;
if (activeProfiles.length == 0 && typeof process._stopProfilerIdleNotifier == "function")
process._stopProfilerIdleNotifier();
return profile;
},
setSamplingInterval: function(num) {
if (activeProfiles.length) {
throw new Error('setSamplingInterval must be called when there are no profiles being recorded.');
}
num = parseInt(num, 10) || 1000;
binding.cpu.setSamplingInterval(num);
},
deleteAllProfiles: function() {
Object.keys(binding.cpu.profiles).forEach(function(key) {
binding.cpu.profiles[key].delete();
});
}
};
module.exports = profiler;
process.profiler = profiler;