• Stars
    star
    2,915
  • Rank 15,557 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ”₯ single-command flamegraph profiling πŸ”₯

0x

0x

πŸ”₯ single-command flamegraph profiling πŸ”₯

Discover the bottlenecks and hot paths in your code, with flamegraphs.

Visualize Stack Traces

0x can profile and generate an interactive flamegraph for a Node process with a single command, on any platform which Node runs on (macOs, Linux, Windows, Android...).

Support

  • Node v12.x and above
  • Default usage supports any Operating System that Node runs on!
  • Chrome
    • Other browsers may open flamegraphs in a degraded, but functional form

Demo

An example interactive flamegraph can be viewed at http://davidmarkclements.github.io/0x-demo/

Install

npm install -g 0x

Usage

Use 0x to run a script:

0x my-app.js

Immediately open the flamegraph in the browser:

0x -o my-app.js

Automatically execute profiling command against the first port opened by profiled process:

0x -P 'autocannon localhost:$PORT' my-app.js

Use a custom node executable:

0x -- /path/to/node my-app.js

Pass custom arguments to node:

0x -- node --zero-fill-buffers my-app.js

for pwsh users, switch to CMD at first or run with npx

npx 0x -o my-app.js

Generating

When ready to generate a flamegraph, send a SIGINT or a SIGTERM.

The simplest way to do this is pressing CTRL+C.

When 0x catches the SIGINT or the SIGTERM, it process the stacks and generates a profile folder (<pid>.0x), containing flamegraph.html.

The UI

The flamegraph.html file contains the 0x UI, which is explained in docs/ui.md.

Production Servers

A lightweight, production server friendly, approach to generating a flamegraph is described in docs/production-servers.md.

The Profile Folder

By default, a Profile Folder will be created and named after the PID, e.g. 3866.0x (we can set this name manually using the --output-dir flag).

The Profile Folder is explained in more detail in docs/profile-folder.md

Example

Clone this repo, run npm i -g and from the repo root run

0x examples/rest-api

In another tab run

npm run stress-rest-example

To put some load on the rest server, once that's done use ctrl + c to kill the server.

Command Line API

--help | -h

Print usage info.

--open | -o

Open the flamegraph in the browser using open or xdg-open (see https://www.npmjs.com/package/open for details).

--on-port | -P

Run a given command and then generate the flamegraph. The command as specified has access to a $PORT variable. The $PORT variable is set according to the first port that profiled process opens.

For instance, here's an example of using autocannon to load-test the process:

0x -P 'autocannon localhost:$PORT' app.js

When the load-test completes, the profiled processed will be sent a SIGINT and the flamegraph will be automatically generated.

Remember to use single quotes to avoid bash interpolation, or else escape variable (e.g. 0x -P "autocannon localhost:$PORT" app.js won't work wheras 0x -P "autocannon localhost:\$PORT" app.js will).

Note: On Windows interpolation usually occurs with %PORT%, however in this case the dollar-prefix $PORT is the correct syntax (because the interpolation is not shell based).

Default: ''

--name

The name of the HTML file, without the .html extension Can be set to - to write HTML to STDOUT (note due to the nature of CLI argument parsing, this must be set using =, e.g. --name=-).

If either this flag or --output-html-file is set to - then the HTML will go to STDOUT.

Default: flamegraph

---title

Set the title to display in the flamegraph UI.

Default: the command that 0x ran to start the process

--output-dir | -D

Specify artifact output directory. This can be specified in template form with possible variables being {pid}, {timestamp}, {name} (based on the --name flag) and {outputDir}(variables must be specified without whitespace, e.g. { pid } is not supported).

Default: {pid}.0x

--output-html | -F

Specify destination of the generated flamegraph HTML file. This can be specified in template form with possible variables being {pid}, {timestamp}, {name} (based on the --name flag) and {outputDir} (variables must be specified without whitespace, e.g. { pid } is not supported). It can also be set to - to send the HTML output to STDOUT (note due to the nature of CLI argument parsing, this must be set using =, e.g. --output-html=-).

If either this flag or --name is set to - then the HTML will go to STDOUT.

Default: {outputDir}/{name}.html

--kernel-tracing

Use an OS kernel tracing tool (perf on Linux). This will capture native stack frames (C++ modules and Libuv I/O), but may result in missing stacks from Node.js due to the optimizing compiler.

See docs/kernel-tracing.md for more information.

Default: false

--quiet | -q

Limit output, the only output will be fatal errors or the path to the flamegraph.html upon successful generation.

Default: false

--silent | -s

Suppress all output, except fatal errors.

Default: false

--collect-only

Don't generate the flamegraph, only create the Profile Folder, with relevant outputs.

Default: false

--collect-delay

Delay the collection of stacks by a specified time(ms) relative to the first entry.

Default: 0

--visualize-only

Supply a path to a profile folder to build or rebuild visualization from original stacks.

Default: undefined

--visualize-cpu-profile

Supply a path to a CPU profile (.cpuprofile). See examples/cpu-profile for examples.

CPU Profile output does not have as much information but it can be exported from Chrome Devtools in the browser. There's also an automated headless tool for doing so: automated-chrome-profiling. For creating Node.js Cpu Profiles in Node see v8-profiler or v8-profiler-next. They can also be generated from Node.js 12 and above using the command-line flag --cpu-prof.

Default: undefined

--kernel-tracing-debug

Show output from perf(1) tools.

Default: false

--tree-debug

Save the intermediate tree representation of captured trace output to a JSON file.

Default: false

Programmatic API

0x can also be required as a Node module and scripted:

const zeroEks = require('0x')
const path = require('path')

async function capture () {
  const opts = {
    argv: [path.join(__dirname, 'my-app.js'), '--my-flag', '"value for my flag"'],
    workingDir: __dirname
  }
  try {
    const file = await zeroEks(opts)
    console.log(`flamegraph in ${file}`)
  } catch (e) {
    console.error(e)
  }
}

capture()

The Programmatic API is detailed in docs/api.md.

Troubleshooting

Memory Issues

Very complex applications with lots of stacks may hit memory issues.

The --stack-size flag can be used to set the memory to the maximum 8GB in order to work around this when profiling:

node --stack-size=8024 $(which 0x) my-app.js

There may still be a problem opening the flamegraph in Chrome. The same work around can be used by opening Chrome from the command line (platform dependent) and nesting the --stack-size flag within the --js-flags flag: --js-flags="--stack-size 8024".

Debugging

DEBUG=0x* 0x my-app.js

Alternatives

Acknowledgements

Sponsored by nearForm

This tool is inspired from various info and code sources and would have taken much longer without the following people and their Open Source/Info Sharing efforts:

License

MIT

More Repositories

1

rfdc

Really Fast Deep Clone
JavaScript
636
star
2

flatstr

Flattens the underlying C structures of a concatenated JavaScript string
JavaScript
346
star
3

fast-safe-stringify

Safely and quickly serialize JavaScript objects
JavaScript
335
star
4

v8-perf

Exploring v8 performance characteristics in Node across v8 versions 5.1, 5.8, 5.9, 6.0 and 6.1
JavaScript
278
star
5

fast-redact

very fast object redaction
JavaScript
274
star
6

overload-protection

Load detection and shedding capabilities for http, express, restify and koa
JavaScript
200
star
7

react-functional

Add life cycle methods to stateless functional components, without the class noise
JavaScript
91
star
8

cute-stack

Cute up your stack traces in Node
JavaScript
82
star
9

atomic-sleep

⏱️Zero CPU overhead, zero dependency, true event-loop blocking sleep ⏱️
JavaScript
78
star
10

brittle

Brittle TAP test framework
JavaScript
57
star
11

Respondu

An Extendible Deferred Asset Responsive Framework
JavaScript
32
star
12

keepings-node.js-fast

Repository accompanying the Keeping Node.js Fast article
JavaScript
31
star
13

screenres

Get and set screen resolutions
C++
20
star
14

decofun

Debug tool. Names anonymous functions according to their surrounding context
JavaScript
18
star
15

lazaretto

Run esm and/or cjs code in a separate V8 isolate with code-injection capabilities
JavaScript
17
star
16

a-new-way-to-profile-node-js

HTML
15
star
17

async-tracer

Trace all async operations, output as newline delimited JSON logs, with minimal overhead.
JavaScript
15
star
18

proffer

Realtime V8 Tick Profiler
JavaScript
13
star
19

websocket-pull-stream

websockets with pull-streams
JavaScript
13
star
20

hsl-to-hex

JavaScript
12
star
21

is-file-esm

Determines whether a Node file is a Module (`import`) or a Script (`require`)
JavaScript
11
star
22

hrepl

Hydrate a REPL with new globals from a file's exports.
JavaScript
11
star
23

d3-fg

Flamegraph visualization for d3 v5
JavaScript
11
star
24

events.once

Polyfill for Node core events.once
JavaScript
11
star
25

nw-shot

Create screenshots using nw.js
JavaScript
10
star
26

core-dump

Generate node core dumps with having to abort, regardless of ulimit -c setting
JavaScript
10
star
27

does-it-fit

Determine whether an HTTP endpoints TCP response fits within minimum constraints
JavaScript
9
star
28

fast-date

Fast UTC Date Timestamps
JavaScript
9
star
29

fastify-react

seamlessly integrate fastify and react, for high performance SSR
JavaScript
9
star
30

nodux

nodux
JavaScript
8
star
31

perf-sym

Map Symbols Generated By --perf-basic-prof to JavaScript names
JavaScript
8
star
32

nonsynchronous

async/await callback fusioning utilities
JavaScript
8
star
33

ubuntu-dev-ec2

Ubuntu EC2 Machine intended for development/profiling usage.
JavaScript
7
star
34

rifi

rifi - distributed single state application self registering components - proof of concept
JavaScript
7
star
35

hash-phrase

A human readable hash function
JavaScript
6
star
36

inclusion

Dynamic imports for all
JavaScript
6
star
37

mockalicious

Keep on mocking in the free world
JavaScript
6
star
38

stateful-hooks

Give your react hooks state on the server side
JavaScript
6
star
39

bespoke-pdf

PDF generating for Bespoke.js
JavaScript
6
star
40

npm-dependents

Command line tool to view the dependents of a module on npm
JavaScript
5
star
41

react-shallow-renderer

Simple wrapper for react-addons-test-utils createRenderer method.
JavaScript
5
star
42

generator-classes

Generator and AsyncGenerator functions|constructors|classes as a module
JavaScript
5
star
43

aquatap

fullstack TAP with a modern API
JavaScript
5
star
44

hyperpdf

Convert Markdown or HTML into PDF's
JavaScript
5
star
45

hn-latest-stream

hackernews stream of latest stories as JSON or HTML
JavaScript
4
star
46

dr-mark

Generate summary docs from repurposed markdown
CSS
4
star
47

pino-trace

Trace all async operations performantly with pino the fast logger
JavaScript
4
star
48

docs-readability

Visual studio code extension for indicating markdown docs readability
JavaScript
4
star
49

nodux-core

nodux-core
JavaScript
3
star
50

bespoke-to-pdf

Generate a PDF file from your bespoke presentation
JavaScript
3
star
51

seneca-scheduler

Seneca scheduler plugin
JavaScript
3
star
52

bespoke-synchro

Synchronize the slide index of bespoke presentation instances
JavaScript
3
star
53

tunl

Securely proxy remote ports to local ports with SSH.
JavaScript
3
star
54

events.on

polyfill for events.on
JavaScript
2
star
55

unijoin

ESM and CJS support for `path.join` of both file paths and file URLs
JavaScript
2
star
56

lucius

Seneca Microservices in the Browser
JavaScript
2
star
57

necropsy

dissect dead node service core dumps with llnode using a single command
Python
2
star
58

react-resolve-render

awaitable React renderToString for stateful Server Side Rendering
JavaScript
2
star
59

qodaa

Quick and Dirty Async/Await for Node 6
JavaScript
1
star
60

vex

A Schema Validator
JavaScript
1
star
61

xmas-gmar

A christmas card I made for my grandmother
HTML
1
star
62

seneca-couchbase-store

Node.js Seneca data storage plugin for Couchbase
JavaScript
1
star
63

proffer-stream-to-realtime-tree

takes proffer data, returns continually updating d3 trees
JavaScript
1
star
64

proc-cpuinfo

Get /proc/cpuinfo as an object
JavaScript
1
star
65

guard-timeout

Guard against sleep mode timeouts firing on wake
JavaScript
1
star
66

graphql-hooks-workshop

HTML
1
star
67

spacey-standard

like standard, but looser line spacing
JavaScript
1
star
68

prompt-sync-history

History manager for `prompt-sync`
JavaScript
1
star
69

postcss-class-whitelist

Remove any class selector not in a provided whitelist
JavaScript
1
star