-
Notifications
You must be signed in to change notification settings - Fork 20
/
cpu.js
54 lines (45 loc) · 1.28 KB
/
cpu.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
// SOURCE: https://gist.github.com/danielkhan/9cfa77b97bc7ba0a3220#file-cpuprofiler-js-L5
/**
* Simple userland CPU profiler using v8-profiler
* Usage: require('[path_to]/CpuProfiler').init('datadir')
*
* @module CpuProfiler
* @type {exports}
*/
var fs = require('fs');
var profiler = require('v8-profiler');
var _datadir = null;
/**
* Init and schedule profiler runs
*
* @param datadir Folder to save the data to
*/
module.exports.init = function (datadir) {
_datadir = datadir;
setInterval(startProfiling, 10 * 1000);
};
/**
* Starts profiling and schedules its end
*/
function startProfiling() {
var stamp = Date.now();
var id = 'profile-' + stamp;
// Use stdout directly to bypass eventloop
fs.writeSync(1, 'Start profiler with Id [' + id + ']\n');
// Start profiling
profiler.startProfiling(id);
// Schedule stop of profiling in x seconds
setTimeout(function () {
stopProfiling(id)
}, 5000);
}
/**
* Stops the profiler and writes the data to a file
* @param id the id of the profiler process to stop
*/
function stopProfiling(id) {
var profile = profiler.stopProfiling(id);
fs.writeFile(_datadir + '/' + id + '.cpuprofile', JSON.stringify(profile), function () {
console.log('Profiler data written');
});
}