-
-
Save Kiran01bm/a3525408ff15c5ba8806af011d4688ce to your computer and use it in GitHub Desktop.
nodejs v8 cpu profiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple userland CPU profiler using v8-profiler | |
* Usage: require('[path_to]/CpuProfiler').init('datadir') | |
* | |
* @module CpuProfiler | |
* @type {exports} | |
*/ | |
var fs = require('fs'); | |
// v8-profiler-node8 is Based on v8-profiler-node8@5.7.0, Solved the v8-profiler segment fault error in node-v8.x. | |
// npm install v8-profiler-node8 | |
var profiler = require('v8-profiler-node8'); | |
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, 30 * 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'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment