stackprof

repository·master·Indexed 24 days ago

https://github.com/tmm1/stackprof

A high-performance sampling call-stack profiler for Ruby designed as a replacement for perftools.rb. It enables developers to identify CPU bottlenecks, object allocation hotspots, and wall-clock time issues. It supports multiple sampling modes (:wall, :cpu, :object, :custom), provides Rack middleware for web applications, and includes a CLI for generating text, JSON, Graphviz, and flamegraph reports.

Tokens
3.5K
Snippets
6
Records
31
Agent score
80%

What's inside stackprof

  1. Configure Sampling Modes and Intervals

    master

    Stackprof supports four sampling modes. You can tune the interval to adjust overhead or granularity.

    Supported Modes

    • :wall: Uses ITIMER_REAL and SIGALRM. This is the default mode. Samples every interval microseconds of wallclock time.
    • :cpu: Uses ITIMER_PROF and SIGPROF. Samples every interval microseconds of CPU activity.
    • :object: Uses RUBY_INTERNAL_EVENT_NEWOBJ. Samples every interval allocations (default interval is 1).
    • :custom: User-defined via StackProf.sample.

    Configuration Options

    • mode: The sampling mode (:wall, :cpu, :object, or :custom).
    • interval: The sampling interval (microseconds for wall/cpu, number of allocations for object).
    • out: Path to save the profile dump.
    • ignore_gc: Set to true to disable explicit garbage collection frames in the profile (useful for long traces to avoid gaps in flamegraphs).
  2. Generate Flamegraphs with Stackprof

    master

    To generate flamegraphs, you must first collect data using the raw: true flag. Once collected, you can generate a flamegraph using the CLI.

    Option 1: Built-in Flamegraph Viewer

    1. Generate the file: $ stackprof --flamegraph tmp/stackprof-cpu-myapp.dump > tmp/flamegraph
    2. Generate a viewer command: $ stackprof --flamegraph-viewer=tmp/flamegraph (this outputs the shell command to open the viewer).

    Option 2: d3-flame-graph Generate an HTML file that can be opened in any browser: $ stackprof --d3-flamegraph tmp/stackprof-cpu-myapp.dump > flamegraph.html

  3. Configure StackProf.run options

    master

    The StackProf.run method accepts an options hash to control the profiling session.

    Key options include:

    • mode: The sampling mode. Supported values are :cpu, :wall, :object, or :custom.
    • out: The file path where the profile data will be written (this file will be overwritten).
    • interval: The mode-relative sample rate.
    • ignore_gc: If set, garbage collection frames will be ignored in the profile.
    • aggregate: Boolean (defaults to true). If false, disables data aggregation.
    • raw: Boolean (defaults to false). If true, collects extra data required for --flamegraph and --stackcollapse report types.
    • metadata: A Hash (defaults to {}) containing metadata associated with the profile.
    • save_every: (Rack middleware only) Specifies how many requests should occur before writing the target file.
  4. Use StackProf::Middleware for Rack applications

    master

    StackProf provides a Rack middleware to profile web applications. When initialized, it configures global StackProf::Middleware settings and can be set to automatically save profile dumps to a specified path.

    To use it, add the middleware to your Rack stack (e.g., in config.ru for Rails or other Rack apps) and pass an options hash to control profiling behavior.

  5. Run Stackprof in Ruby

    master

    Use StackProf.run to profile a specific block of code. This method returns a profile hash containing the sampling data.

    StackProf.run(mode: :cpu, out: 'tmp/stackprof-cpu-myapp.dump') do
      #... your code to profile ...
    end
    StackProf.run(mode: :cpu, out: 'tmp/stackprof-cpu-myapp.dump') do
      #...
    end
  6. Manually Control Stackprof Lifecycle

    master

    For more control, you can start and stop the profiler manually. Results are accumulated across multiple start/stop calls until you retrieve them.

    StackProf.running? # => false
    StackProf.start(mode: :cpu)
    StackProf.running? # => true
    StackProf.stop
    StackProf.results('/tmp/some.file')
  7. Report Profile Data

    master

    Once you have profile data (the hash returned by StackProf.run), you can generate reports using StackProf::Report.

    Text Reporting

    Use .print_text for a standard text-based summary in the console.

    StackProf::Report.new(data).print_text

    Graphviz Reporting

    Use .print_graphviz to generate a DOT format string for visualizing the call graph.

    StackProf::Report.new(data).print_graphviz

    Method-Specific Reporting

    Use .print_method to see details for specific methods (supports regex/patterns).

    StackProf::Report.new(data).print_method(/pow|newobj|math/)
  8. Configure StackProf::Middleware options

    master

    When initializing StackProf::Middleware, you can provide the following options:

    OptionTypeDefaultDescription
    :enabledBoolean or ProcnilDetermines if profiling is active. If a Proc is provided, it is called with the Rack env to decide whether to profile the current request.
    :modeSymbol:cpuThe profiling mode (e.g., :cpu, :wall).
    :intervalInteger1000The sampling interval in microseconds.
    :rawBooleanfalseWhether to collect raw data.
    :pathString'tmp/'The directory or filename where profile dumps are saved.
    :metadataHash{}Metadata to include in the profile.
    :save_everyIntegernilIf set, the middleware will save a profile dump every N requests.
    :save_at_exitBooleanfalseIf true, triggers StackProf::Middleware.save when the process exits.