Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Helper to record node CPU profiles, which can be easily viewed as CPU flame graphs using Chrome debugger
// Helper to record CPU profiles
// 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('\nStart profiling with "kill -PIPE ' + + '"');
console.log('Stop profiling with the same command.');
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);
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