### Install ruby-prof Source: https://ruby-prof.github.io/profiling-rails Run the bundle command to install the newly added gem. ```bash bundle install ``` -------------------------------- ### Start Rails in profile environment Source: https://ruby-prof.github.io/profiling-rails Launch the Rails server or console using the profile environment. ```bash bin/rails server -e profile ``` ```bash bin/rails console -e profile ``` -------------------------------- ### Example code for call tree construction Source: https://ruby-prof.github.io/architecture A simple Ruby example demonstrating method calls that result in multiple call sites for the same method. ```ruby def process validate save end def save validate write end ``` -------------------------------- ### Install ruby-prof gem Source: https://ruby-prof.github.io/ Use this command to install the ruby-prof gem via RubyGems. ```bash gem install ruby-prof ``` -------------------------------- ### Generate ruby-prof example reports Source: https://ruby-prof.github.io/reports Executes the report generation script to profile a word-frequency workload. ```bash ruby docs/public/examples/generate_reports.rb ``` -------------------------------- ### Profile using Convenience API Source: https://ruby-prof.github.io/getting-started Use the RubyProf::Profile class to manually start and stop profiling, or use the block-based profile method. ```ruby require 'ruby-prof' profile = RubyProf::Profile.new # profile the code profile.start # ... code to profile ... result = profile.stop # print a flat profile to text printer = RubyProf::FlatPrinter.new(result) printer.print(STDOUT) ``` ```ruby require 'ruby-prof' # profile the code result = RubyProf::Profile.profile do # ... code to profile ... end # print a graph profile to text printer = RubyProf::GraphPrinter.new(result) printer.print(STDOUT) ``` -------------------------------- ### Configure profile environment Source: https://ruby-prof.github.io/profiling-rails Set up the profile environment by inheriting from production and adding the Rack::RubyProf middleware. ```ruby # config/environments/profile.rb require_relative "production" Rails.application.configure do # Optional: reduce noise while profiling. config.log_level = :warn # Optional: disable controller/view caching if you want raw app execution timing. config.action_controller.perform_caching = false config.middleware.use Rack::RubyProf, path: Rails.root.join("tmp/profile") end ``` -------------------------------- ### Update printer options to keyword arguments Source: https://ruby-prof.github.io/changelog Demonstrates the transition from using an options hash to keyword arguments for printer methods. ```ruby # Before: printer.print(STDOUT, :min_percent => 2, :sort_method => :self_time) # After: printer.print(STDOUT, min_percent: 2, sort_method: :self_time) ``` -------------------------------- ### Generate a GraphPrinter report Source: https://ruby-prof.github.io/reports Create a report by initializing a printer with a profile object and printing to an IO stream. The min_percent option filters methods based on their self-time contribution. ```ruby profile = RubyProf::Profile.profile do ... end printer = RubyProf::GraphPrinter.new(profile) printer.print(STDOUT, min_percent: 2) ``` -------------------------------- ### Configure Core API Source: https://ruby-prof.github.io/getting-started Initialize the RubyProf::Profile class directly to access advanced features like custom measurement modes. ```ruby require 'ruby-prof' profile = RubyProf::Profile.new(measure_mode: RubyProf::WALL_TIME) result = profile.profile do ... end ``` -------------------------------- ### Initialize a Profile object Source: https://ruby-prof.github.io/architecture Use the profile block to initiate a profiling run and capture method execution data. ```ruby profile = RubyProf::Profile.profile do ... end ``` -------------------------------- ### Inspect generated reports Source: https://ruby-prof.github.io/profiling-rails List the files generated in the profile output directory. ```bash ls -1 tmp/profile ``` -------------------------------- ### Manage visit counters on method entry and exit Source: https://ruby-prof.github.io/architecture C-level logic for tracking method visits to detect recursion and manage stack state. ```c // Method entry (prof_frame_push): call_tree->visits++; if (call_tree->method->visits > 0) call_tree->method->recursive = true; call_tree->method->visits++; // Method exit (prof_frame_pop): call_tree->visits--; call_tree->method->visits--; ``` -------------------------------- ### Generate profile output Source: https://ruby-prof.github.io/profiling-rails Trigger a request to the server to generate the profiling reports. ```bash curl http://127.0.0.1:3000/ ``` -------------------------------- ### Run ruby-prof via Command Line Source: https://ruby-prof.github.io/getting-started Execute profiling directly from the terminal without modifying source code. ```bash ruby-prof [options] [--] [script-options] ``` ```bash ruby-prof -h ``` -------------------------------- ### Set Measurement Mode via Environment Variable Source: https://ruby-prof.github.io/advanced-usage Configures the measurement mode using the RUBY_PROF_MEASURE_MODE environment variable. ```bash export RUBY_PROF_MEASURE_MODE=wall export RUBY_PROF_MEASURE_MODE=process export RUBY_PROF_MEASURE_MODE=allocations ``` -------------------------------- ### Enable Allocation Tracking Source: https://ruby-prof.github.io/advanced-usage Use the track_allocations option to enable detailed object allocation reporting. ```ruby require 'ruby-prof' RubyProf::Profile.profile(track_allocations: true) do ... end ``` -------------------------------- ### Generate a Flame Graph report Source: https://ruby-prof.github.io/reports Creates an HTML file containing a flame graph visualization of the profiling results. ```ruby printer = RubyProf::FlameGraphPrinter.new(result) printer.print(File.open("flame_graph.html", "w")) ``` -------------------------------- ### Enable fiber merging in Rack middleware Source: https://ruby-prof.github.io/advanced-usage Configures the Rack adapter to merge fiber results automatically. ```ruby config.middleware.use Rack::RubyProf, path: Rails.root.join("tmp/profile"), merge_fibers: true ``` -------------------------------- ### Printer.print(io, options) Source: https://ruby-prof.github.io/reports Generates a report from a RubyProf::Profile object using a specific printer class. The printer is initialized with the profile and outputs to the provided IO object. ```APIDOC ## Printer.print(io, options) ### Description Generates a profiling report based on the profile data provided during initialization. The output is written to the specified IO object, such as STDOUT or a file. ### Parameters - **io** (IO) - Required - A writable IO object where the report will be written. - **min_percent** (Float) - Optional - Minimum %self time for a method to be included (0–100). Default: 0. - **max_percent** (Float) - Optional - Maximum %self time for a method to be included (0–100). Default: 100. - **filter_by** (Symbol) - Optional - Which time metric to use when applying min_percent and max_percent. Default: :self_time. - **sort_method** (Symbol) - Optional - How to sort methods. Values: :total_time, :self_time, :wait_time, :children_time. - **max_depth** (Integer) - Optional - Maximum call tree depth to display. Applies to FlameGraphPrinter, CallStackPrinter, and CallInfoPrinter. Default: nil. ### Request Example printer = RubyProf::GraphPrinter.new(profile) printer.print(STDOUT, min_percent: 2) ``` -------------------------------- ### Pause and Resume Profiling Source: https://ruby-prof.github.io/changelog Use RubyProf.resume with a block to automatically pause profiling after the block execution. ```ruby 10.times do |i| RubyProf.resume do # Some long process end end result = RubyProf.stop ``` -------------------------------- ### Graphviz DOT Profile Representation Source: https://ruby-prof.github.io/public/examples/reports/graphviz_viewer.html A DOT language representation of a ruby-prof call graph, defining nodes for methods and edges for call relationships with performance metrics. ```dot digraph "Profile" { rankdir=TB; bgcolor="#FAFAFA"; node [fontname="Helvetica" fontsize=11 style="filled,rounded" shape=box fillcolor="#FFFFFF" color="#CCCCCC" penwidth=1.2]; edge [fontname="Helvetica" fontsize=9 color="#5B7DB1" arrowsize=0.7]; labelloc=t; labeljust=l; subgraph "Thread 464" { 624 [label="take\n(0%)"]; 632 [label="-@\n(0%)"]; 640 [label="each\n(0%)"]; 640 -> 632 [label="25/25" penwidth=0.5]; 648 [label="sort_by\n(0%)"]; 648 -> 640 [label="1/1" penwidth=0.5]; 656 [label="top_words\n(0%)"]; 656 -> 648 [label="1/1" penwidth=0.5]; 656 -> 624 [label="1/1" penwidth=0.5]; 664 [label="[]=\n(13%)" fillcolor="#2E86C1" fontcolor="#FFFFFF"]; 672 [label="+\n(9%)" fillcolor="#D4E6F1" fontcolor="#333333"]; 680 [label="[]\n(11%)" fillcolor="#2E86C1" fontcolor="#FFFFFF"]; 688 [label="each\n(72%)" fillcolor="#0D2483" fontcolor="#FFFFFF"]; 688 -> 664 [label="5800/5800" penwidth=1.1]; 688 -> 680 [label="5800/5800" penwidth=1.1]; 688 -> 672 [label="5800/5800" penwidth=0.9]; 696 [label="initialize\n(0%)"]; 704 [label="count_words\n(72%)" fillcolor="#0D2483" fontcolor="#FFFFFF"]; 704 -> 688 [label="1/1" penwidth=4.0]; 704 -> 696 [label="1/1" penwidth=0.5]; 712 [label="split\n(19%)" fillcolor="#2E86C1" fontcolor="#FFFFFF"]; 720 [label="tokenize\n(19%)" fillcolor="#2E86C1" fontcolor="#FFFFFF"]; 720 -> 712 [label="1/1" penwidth=1.5]; 728 [label="gsub\n(8%)" fillcolor="#D4E6F1" fontcolor="#333333"]; 736 [label="downcase\n(0%)"]; 744 [label="normalize\n(8%)" fillcolor="#D4E6F1" fontcolor="#333333"]; 744 -> 728 [label="1/1" penwidth=0.9]; 744 -> 736 [label="1/1" penwidth=0.5]; 752 [label="*\n(0%)"]; 760 [label="run_example\n(100%)" fillcolor="#0D2483" fontcolor="#FFFFFF"]; 760 -> 704 [label="1/1" penwidth=4.0]; 760 -> 720 [label="1/1" penwidth=1.5]; 760 -> 744 [label="1/1" penwidth=0.9]; 760 -> 656 [label="1/1" penwidth=0.5]; 760 -> 752 [label="1/1" penwidth=0.5]; 768 [label="[global]\n(100%)" fillcolor="#0D2483" fontcolor="#FFFFFF"]; 768 -> 760 [label="1/1" penwidth=4.0]; } subgraph cluster_776 { label = "[global]"; fontname = "Helvetica"; fontcolor = "#1A35A6"; fontsize = 14; color = "#1A35A6"; style = "rounded,dashed"; penwidth = 1.5; 768; } subgraph cluster_784 { label = "Object"; fontname = "Helvetica"; ``` -------------------------------- ### Pause and Resume Profiling Source: https://ruby-prof.github.io/getting-started Control profiling execution flow by pausing and resuming during runtime. ```ruby require 'ruby-prof' profile = RubyProf::Profile.new # profile the code profile.start # ... code to profile ... profile.pause # ... other code ... profile.resume # ... code to profile ... result = profile.stop ``` ```ruby require 'ruby-prof' profile = RubyProf::Profile.new # profile the code profile.start # ... code to profile ... profile.pause # ... other code ... profile.resume do # ... code to profile... end result = profile.stop ``` -------------------------------- ### Merge threads and fibers in ruby-prof Source: https://ruby-prof.github.io/advanced-usage Collapses results for threads and fibers sharing the same root method into a single entry. ```ruby profile = RubyProf::Profile.profile do ... end profile.merge! ``` -------------------------------- ### Persist profile results using Marshal Source: https://ruby-prof.github.io/advanced-usage Saves and loads profiling data using Ruby's Marshal library. Ensure data sources are trusted to prevent arbitrary code execution. ```ruby profile_1 = RubyProf::Profile.profile do ... end # Save the results data = Marshal.dump(profile_1) # Sometime later load the results profile_2 = Marshal.load(data) ``` -------------------------------- ### Set Measurement Mode in Ruby Source: https://ruby-prof.github.io/advanced-usage Configures the measurement mode during the initialization of a RubyProf::Profile object. ```ruby profile = RubyProf::Profile.new(measure_mode: RubyProf::WALL_TIME) profile = RubyProf::Profile.new(measure_mode: RubyProf::PROCESS_TIME) profile = RubyProf::Profile.new(measure_mode: RubyProf::ALLOCATIONS) ``` -------------------------------- ### Enable Profiling in Test::Unit Source: https://ruby-prof.github.io/changelog Include the RubyProf::Test module in a test class to enable profiling for that test suite. ```ruby include RubyProf::Test ``` -------------------------------- ### Lookup or create child CallTree node Source: https://ruby-prof.github.io/architecture Checks the parent's children hash table for an existing CallTree node; creates a new one if it does not exist. ```c call_tree = call_tree_table_lookup(parent_call_tree->children, method->key); if (!call_tree) { call_tree = prof_call_tree_create(method, parent_call_tree, ...); prof_call_tree_add_child(parent_call_tree, call_tree); } ``` -------------------------------- ### Generate multiple reports simultaneously Source: https://ruby-prof.github.io/reports Uses the MultiPrinter to output several report formats in a single profiling run to a specified directory. ```ruby printer = RubyProf::MultiPrinter.new(result) printer.print(path: ".", profile: "profile") ``` -------------------------------- ### Accumulate total time at outermost visit Source: https://ruby-prof.github.io/architecture C-level logic to prevent double-counting of time by only accumulating measurements when the visit count is 1. ```c // Only accumulate total_time at the outermost visit if (call_tree->visits == 1) call_tree->measurement->total_time += total_time; if (call_tree->method->visits == 1) call_tree->method->measurement->total_time += total_time; ``` -------------------------------- ### RubyProf Printer Classes Source: https://ruby-prof.github.io/reports Overview of the available printer classes used to generate reports from profiling results. ```APIDOC ## RubyProf Printer Classes ### Description RubyProf provides several printer classes to output profiling results in different formats. Each printer is initialized with a `result` object and provides a `print` method. ### Available Printers - **RubyProf::FlatPrinter**: Generates a flat report showing overall time per method. - **RubyProf::GraphPrinter**: Generates a text-based graph report showing call relationships. - **RubyProf::GraphHtmlPrinter**: Generates an HTML-based graph report with hyperlinks. - **RubyProf::FlameGraphPrinter**: Generates an interactive HTML flame graph visualization. - **RubyProf::CallStackPrinter**: Generates an HTML visualization of execution paths. - **RubyProf::DotPrinter**: Generates output for Graphviz visualization. - **RubyProf::CallTreePrinter**: Generates output in the calltree format for KCachegrind. - **RubyProf::CallInfoPrinter**: Generates a call tree report with timing information for debugging. - **RubyProf::MultiPrinter**: Generates multiple report types in a single run. ### Usage Example ```ruby printer = RubyProf::FlameGraphPrinter.new(result) printer.print(File.open("flame_graph.html", "w")) ``` ``` -------------------------------- ### Define a recursive method for call tree analysis Source: https://ruby-prof.github.io/architecture A simple recursive Ruby method used to demonstrate how new CallTree nodes are generated at each recursion level. ```ruby def simple(n) sleep(1) return if n == 0 simple(n - 1) end simple(2) ``` -------------------------------- ### Add ruby-prof to Gemfile Source: https://ruby-prof.github.io/profiling-rails Include the ruby-prof gem within a specific profile group in your Gemfile. ```ruby group :profile do gem 'ruby-prof' end ``` -------------------------------- ### Exclude Common Methods Source: https://ruby-prof.github.io/advanced-usage Use a predefined set of common methods to exclude from profiling results. ```ruby profile.exclude_common_methods! ``` -------------------------------- ### Retrieve parent CallTree node Source: https://ruby-prof.github.io/architecture Retrieves the parent CallTree node from the current stack frame during a method call event. ```c parent_call_tree = frame->call_tree; ``` -------------------------------- ### Exclude Methods from Profiling Source: https://ruby-prof.github.io/advanced-usage Remove specific methods from the call graph to reduce noise and focus on relevant performance data. ```ruby profile = RubyProf::Profile.new(...) profile.exclude_methods!(Integer, :times, ...) profile.start ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.