Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kimmobrunfeldt
Last active October 26, 2016 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimmobrunfeldt/f7dddeb171535dcabb5befd0e0de122b to your computer and use it in GitHub Desktop.
Save kimmobrunfeldt/f7dddeb171535dcabb5befd0e0de122b to your computer and use it in GitHub Desktop.
Helper to record node CPU profiles, which can be easily viewed as CPU flame graphs using Chrome debugger
// Helper to record CPU profiles
// https://github.com/node-inspector/v8-profiler#cpu-profile-api
//
// Usage:
// 1. npm install v8-profiler
// 2. require('./cpu-profile-trigger') once in your app code
// 3. Start CPU profiling with kill -PIPE <pid>. Instructions will be logged to stdout.
// 4. Stop CPU profiling with running again kill -PIPE <pid>
// 5. Go to Chrome debugger, open Profiles tab. Click Load and
// open the <timestamp>.cpuprofile. It was saved to the same dir
// where you started your app.
// 6. Open the CPU profile. You might want to change the view to "Chart".
// Default view is usually "Heavy (Bottom Up)" or "Tree (Top Down)".
var fs = require('fs');
var profiler = require('v8-profiler');
console.log('\n\n-----------------------------------------------------------');
console.log('CPU PROFILE RECORD TRIGGER LISTENING ..\n');
console.log('\nStart profiling with "kill -PIPE ' + process.pid + '"');
console.log('Stop profiling with the same command.');
console.log('-----------------------------------------------------------\n\n');
var callCount = 0;
process.on('SIGPIPE', function() {
console.log('Received SIGPIPE signal.');
var startTimestamp = timestamp();
if (callCount % 2 === 0) {
console.log('Start profiling ..');
profiler.startProfiling(startTimestamp, true);
} else {
console.log('Stop profiling ..');
var profile1 = profiler.stopProfiling();
profile1.export(function(error, result) {
const fileName = startTimestamp + '.cpuprofile';
fs.writeFileSync(fileName, result);
console.log('Saved CPU profile as ' + fileName);
profile1.delete();
});
}
++callCount;
});
function timestamp() {
return (new Date()).toISOString().split('.')[0].replace(/:/g, '-');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment