├── .editorconfig ├── .eslintrc ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs ├── demo.gif ├── flame.gif └── readme.md ├── examples ├── dumb-cpu.js ├── express.js ├── leak-memory.js └── loop-noop.js ├── package.json └── src └── index.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | end_of_line = lf 8 | insert_final_newline = true 9 | indent_style = space 10 | indent_size = 2 11 | 12 | [Makefile] 13 | indent_style = tab 14 | indent_size = 4 15 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base", 3 | "env": { 4 | "mocha": true 5 | }, 6 | "rules": { 7 | "import/no-extraneous-dependencies": ["error", {"devDependencies": true}] 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | *.cpuprofile 5 | *.heapsnapshot 6 | 7 | # Runtime data 8 | pids 9 | *.pid 10 | *.seed 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | 18 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 19 | .grunt 20 | 21 | # Compiled binary addons (http://nodejs.org/api/addons.html) 22 | build/Release 23 | 24 | # Dependency directory 25 | # Deployed apps should consider commenting this line out: 26 | # see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | # OS X 30 | .DS_Store 31 | 32 | # Vagrant directory 33 | .vagrant 34 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 6 4 | - 5 5 | - 4 6 | notifications: 7 | email: 8 | - kimmobrunfeldt+node@gmail.com 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Pull requests and contributions are warmly welcome. 4 | Please follow existing code style and commit message conventions. 5 | Remember to keep documentation updated. 6 | 7 | **Pull requests:** You don't need to bump version numbers or modify anything 8 | related to releasing. That stuff is fully automated, just write the functionality. 9 | 10 | # Maintaining 11 | 12 | ## Release 13 | 14 | * Commit all changes 15 | * Run `./node_modules/.bin/releasor --bump minor`, which will create new tag and publish code to GitHub and npm 16 | 17 | See [releasor documentation](https://github.com/kimmobrunfeldt/releasor) 18 | for detailed usage. 19 | 20 | * Edit GitHub release notes 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Kimmo Brunfeldt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # v8-profiler-trigger 2 | 3 | > Trigger CPU profile recording or heap snapshots for node apps using keyboard 4 | shortcuts. 5 | 6 | [![NPM Badge](https://nodei.co/npm/v8-profiler-trigger.png?downloads=true)](https://www.npmjs.com/package/v8-profiler-trigger) 7 | 8 | **Taking a heap snapshot** 9 | 10 | ![Demo](docs/demo.gif) 11 | 12 | 1. Start v8-profiler-trigger once in your app 13 | 14 | ```js 15 | const v8ProfilerTrigger = require('v8-profiler-trigger'); 16 | v8ProfilerTrigger(); 17 | ``` 18 | 19 | 2. Press `h` followed by enter 20 | 3. Thats it, you can now load the saved *.heapsnapshot* to Chrome debugger 21 | 22 | In debugger, open `Profiles` tab. Click Load and 23 | open the .heapsnapshot. 24 | 25 | 26 | ## Install 27 | 28 | ```bash 29 | npm install v8-profiler-trigger --save-dev 30 | ``` 31 | 32 | ## API 33 | 34 | ### v8ProfilerTrigger([opts]) 35 | 36 | Starts the V8 profiler trigger listeners. 37 | 38 | 39 | #### `opts` 40 | 41 | ```js 42 | { 43 | // Trigger snapshots or recording via stdin events. 44 | // The only method supported currently is 'stdin'. 45 | listenMethod: 'stdin', 46 | 47 | // Changes default CPU profiler sampling interval to the specified 48 | // number of microseconds. Default interval is 1000us. 49 | samplingInterval: 1000 50 | } 51 | ``` 52 | 53 | ## Usage 54 | 55 | Examples how to use the v8-profiler. 56 | 57 | ### CPU Profiling 58 | 59 | You can use Chrome debugger to interactively inspect results: 60 | 61 | ![Flamegraph](docs/flame.gif) 62 | 63 | 64 | ## License 65 | 66 | MIT 67 | -------------------------------------------------------------------------------- /docs/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kimmobrunfeldt/v8-profiler-trigger/e07348166cfdb1c4603769aae74cdaa536203d41/docs/demo.gif -------------------------------------------------------------------------------- /docs/flame.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kimmobrunfeldt/v8-profiler-trigger/e07348166cfdb1c4603769aae74cdaa536203d41/docs/flame.gif -------------------------------------------------------------------------------- /docs/readme.md: -------------------------------------------------------------------------------- 1 | # CPU Profiling 2 | 3 | Practical introduction to CPU profiling Node apps. 4 | 5 | **Remember**, Node uses a single thread. CPU processing blocks all other tasks. 6 | In HTTP context, doing CPU work blocks all other requests. 7 | 8 | ## Tools 9 | 10 | * Native ways in Node 6+ 11 | 12 | * `--inspect` *My recommendation for start* 13 | * `--prof`, `--prof-process` *For deeper investigation* 14 | 15 | https://nodejs.org/en/docs/guides/simple-profiling/ 16 | 17 | > There are many third party tools available for profiling Node.js applications but, in many cases, the easiest option is to use the Node.js built in profiler. 18 | 19 | To me, importing the .cpuprofile to a graphical debugger feels much easier. 20 | 21 | * [v8-profiler](https://github.com/node-inspector/v8-profiler) 22 | 23 | Profiling can be triggered from code. 24 | 25 | [v8-profiler-trigger](https://github.com/kimmobrunfeldt/v8-profiler-trigger) 26 | for those times when `--inspect` just doesn't work or is slow as hell. 27 | 28 | 29 | 30 | ## Resources 31 | 32 | **V8 optimization** 33 | 34 | * https://github.com/thlorenz/v8-perf/blob/master/performance-profiling.md 35 | * https://github.com/petkaantonov/bluebird/wiki/Optimization-killers 36 | * https://github.com/vhf/v8-bailout-reasons 37 | * More detailed V8 profiling: https://gist.github.com/kevincennis/0cd2138c78a07412ef21 38 | -------------------------------------------------------------------------------- /examples/dumb-cpu.js: -------------------------------------------------------------------------------- 1 | const v8ProfilerTrigger = require('../src/index'); 2 | v8ProfilerTrigger(); 3 | 4 | function slow(factor) { 5 | for (var i = 0; i < Math.pow(2, factor); ++i) { 6 | // no op 7 | } 8 | } 9 | 10 | function iteration(i) { 11 | console.log('Running slow(' + i + ')'); 12 | slow(i); 13 | 14 | setTimeout(function() { 15 | iteration(i + 1); 16 | }, 500); 17 | } 18 | 19 | console.log('Using CPU in a very dumb way ..'); 20 | iteration(10); 21 | -------------------------------------------------------------------------------- /examples/express.js: -------------------------------------------------------------------------------- 1 | const app = require('express')(); 2 | const request = require('request'); 3 | const v8ProfilerTrigger = require('../src/index'); 4 | v8ProfilerTrigger(); 5 | 6 | function slow(factor) { 7 | for (let i = 0; i < Math.pow(10, factor); ++i) { 8 | // blocking the event loop 9 | } 10 | } 11 | 12 | app.get(['/slow', `/${encodeURIComponent('🐢')}`], (req, res, next) => { 13 | slow(8); 14 | slow(8); 15 | res.json({ success: true }); 16 | }); 17 | 18 | app.get(['/fast', `/${encodeURIComponent('🚀')}`], (req, res, next) => { 19 | res.json({ success: true }); 20 | }); 21 | 22 | app.get(['/github-search', `/${encodeURIComponent('🔍')}`], (req, res, next) => { 23 | request('https://api.github.com/search/repositories', { 24 | qs: req.query, 25 | headers: { 26 | // Github API requires user agent 27 | 'user-agent': 'test' 28 | } 29 | }) 30 | .pipe(res); 31 | }); 32 | 33 | app.listen(3000, () => { 34 | console.log('Listening at http://localhost:3000 ..\n'); 35 | console.log('Slow no-op'); 36 | console.log(' http get localhost:3000/🐢\n'); 37 | console.log('Fast no-op'); 38 | console.log(' http get localhost:3000/🚀\n'); 39 | console.log('Github search'); 40 | console.log(' http get localhost:3000/🔍'); 41 | }); 42 | -------------------------------------------------------------------------------- /examples/leak-memory.js: -------------------------------------------------------------------------------- 1 | const v8ProfilerTrigger = require('../src/index'); 2 | v8ProfilerTrigger(); 3 | 4 | console.log('Filling array with useless objects ..'); 5 | 6 | let array = []; 7 | setInterval(function() { 8 | array.push(new MyObject()); 9 | if (array.length % 100 === 0) { 10 | console.log(array.length + ' items added'); 11 | } 12 | }, 10); 13 | 14 | function MyObject() { 15 | this.a = 1; 16 | } 17 | 18 | MyObject.prototype.getA = function getA() { 19 | return this.a; 20 | }; 21 | -------------------------------------------------------------------------------- /examples/loop-noop.js: -------------------------------------------------------------------------------- 1 | const v8ProfilerTrigger = require('../src/index'); 2 | v8ProfilerTrigger(); 3 | 4 | console.log('Starting eternal interval of no ops ..') 5 | setInterval(function() { 6 | console.log('no op.'); 7 | }, 1000); 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "v8-profiler-trigger", 3 | "version": "1.0.1", 4 | "description": "Trigger CPU profile recording or heap snapshots for node apps using keyboard shortcuts", 5 | "main": "src/index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/kimmobrunfeldt/v8-profiler-trigger.git" 9 | }, 10 | "keywords": [ 11 | "v8", 12 | "profile", 13 | "heapdump", 14 | "profiler", 15 | "flamegraph", 16 | "cpu" 17 | ], 18 | "author": "Kimmo Brunfeldt", 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/kimmobrunfeldt/v8-profiler-trigger/issues" 22 | }, 23 | "homepage": "https://github.com/kimmobrunfeldt/v8-profiler-trigger#readme", 24 | "dependencies": { 25 | "bluebird": "^3.4.6", 26 | "chalk": "^1.1.3", 27 | "keypress": "^0.2.1", 28 | "v8-profiler": "^5.6.5" 29 | }, 30 | "devDependencies": { 31 | "eslint": "^3.5.0", 32 | "eslint-config-airbnb-base": "^7.1.0", 33 | "eslint-plugin-import": "^1.15.0", 34 | "mocha": "^3.0.2", 35 | "releasor": "^1.2.1" 36 | }, 37 | "scripts": { 38 | "lint": "eslint ./src ./test" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | const BPromise = require('bluebird'); 3 | const chalk = require('chalk'); 4 | const fs = BPromise.promisifyAll(require('fs')); 5 | const profiler = BPromise.promisifyAll(require('v8-profiler')); 6 | 7 | function listen(opts) { 8 | opts = _.merge({ 9 | listenMethod: 'stdin', 10 | 11 | // Changes default CPU profiler sampling interval to the specified 12 | // number of microseconds. Default interval is 1000us. 13 | samplingInterval: 1000, 14 | }, opts); 15 | 16 | profiler.setSamplingInterval(opts.samplingInterval); 17 | 18 | if (opts.listenMethod === 'stdin') { 19 | listenStdin(opts); 20 | } 21 | } 22 | 23 | function listenStdin(opts) { 24 | console.log('\n'); 25 | console.log([ 26 | chalk.gray('-----------------'), 27 | chalk.gray.bold('v8-profiler-trigger'), 28 | chalk.gray('-----------------------') 29 | ].join('')); 30 | console.log(chalk.italic.gray('\n Press any of the characters below followed by enter\n')); 31 | console.log(chalk.red.bold(' (c) '), 'Toggle CPU profiling'); 32 | console.log(chalk.blue.bold(' (h) '), 'Save heap snapshot\n'); 33 | console.log(chalk.gray('-----------------------------------------------------------\n\n')); 34 | 35 | process.stdin.resume(); 36 | process.stdin.setEncoding('utf-8'); 37 | process.stdin.on('data', function(key) { 38 | switch (key.trim()) { 39 | case 'c': 40 | return toggleCpuProfiler(); 41 | case 'h': 42 | return saveHeapSnapshot(); 43 | } 44 | }); 45 | } 46 | 47 | let cpuProfilerRunning = false; 48 | let cpuProfilerStartTimestamp; 49 | function toggleCpuProfiler() { 50 | if (!cpuProfilerRunning) { 51 | logGray('Start CPU profiling ..'); 52 | 53 | cpuProfilerStartTimestamp = timestamp(); 54 | profiler.startProfiling(cpuProfilerStartTimestamp, true); 55 | cpuProfilerRunning = true; 56 | } else { 57 | logGray('Saving CPU profile ..'); 58 | const profile = BPromise.promisifyAll(profiler.stopProfiling()); 59 | profile.exportAsync() 60 | .then(function(result) { 61 | const fileName = cpuProfilerStartTimestamp + '.cpuprofile'; 62 | 63 | return BPromise.props({ 64 | write: fs.writeFileAsync(fileName, result), 65 | fileName: fileName 66 | }); 67 | }) 68 | .then(function(res) { 69 | logGray('Saved CPU profile as ' + res.fileName); 70 | profile.delete(); 71 | }); 72 | 73 | cpuProfilerRunning = false; 74 | } 75 | } 76 | 77 | function saveHeapSnapshot() { 78 | logGray('Saving heap snapshot ..'); 79 | 80 | const snapshot = BPromise.promisifyAll(profiler.takeSnapshot()); 81 | snapshot.exportAsync() 82 | .then(function(result) { 83 | const fileName = timestamp() + '.heapsnapshot'; 84 | 85 | return BPromise.props({ 86 | write: fs.writeFileAsync(fileName, result), 87 | fileName: fileName 88 | }); 89 | }) 90 | .then(function(res) { 91 | logGray('Saved heap snapshot as ' + res.fileName); 92 | snapshot.delete(); 93 | }); 94 | } 95 | 96 | function logGray(/* arguments */) { 97 | const args = Array.prototype.slice.call(arguments); 98 | console.log.apply(this, args.map(function(i) { 99 | return chalk.gray(i); 100 | })); 101 | } 102 | 103 | function timestamp() { 104 | return (new Date()).toISOString().split('.')[0].replace(/:/g, '-'); 105 | } 106 | 107 | module.exports = listen; 108 | --------------------------------------------------------------------------------