Profiling

suggest change

A benchmark tells you how long some code takes. A profiler tells you where the time (or memory) goes. When a program is slow, guessing which method to optimize is usually wrong. Profile first, fix the hottest spot, then measure again.

Ruby has three kinds of profilers:

Kind How it works Overhead Tools
Sampling Records the call stack every N microseconds Low (a few %), safe for production stackprof, vernier
Tracing Hooks every method call and return High (often 5-20x slower) ruby-prof, TracePoint
Memory Records every object allocation High memory_profiler, ObjectSpace

Sampling profilers tell you where the time goes, with statistical accuracy. Tracing profilers also give exact call counts, but they slow down cheap methods more than expensive ones, which skews the results. Memory profilers show which lines allocate objects and which objects stay alive.

For comparing two implementations of the same thing, see Benchmarks.

The examples were run with Ruby 4.0, stackprof 0.2.28, vernier 1.11, ruby-prof 2.0 and memory_profiler 1.1. Times and sample counts depend on your machine, so treat the numbers below as illustrations.

Installing

# Gemfile
group :development do
  gem "stackprof", "~> 0.2"
  gem "vernier", "~> 1.11"        # Ruby 3.2.1+, Linux and macOS
  gem "ruby-prof", "~> 2.0"
  gem "memory_profiler", "~> 1.1"
end

All except memory_profiler are C extensions, so you need a compiler. stackprof and vernier don't work on Windows. Use WSL there.

A slow program to profile

All examples profile this program:

# report.rb - a deliberately slow program
Order = Struct.new(:id, :customer, :amount)

def load_orders(n)
  Array.new(n) { |i| Order.new(i, "customer-#{i % 500}", (i * 37) % 1000) }
end

def slugify(name)
  name.downcase.gsub(/[^a-z0-9]+/, "-")
end

def totals_by_customer(orders)
  orders.group_by { |o| slugify(o.customer) }
        .transform_values { |os| os.sum(&:amount) }
end

def top_customers(orders, k)
  # O(n * m): scans all orders for every customer
  customers = orders.map(&:customer).uniq
  customers.map { |c| [c, orders.select { |o| o.customer == c }.sum(&:amount)] }
           .sort_by { |_, total| -total }
           .first(k)
end

def build_report(n)
  orders = load_orders(n)
  totals = totals_by_customer(orders)
  top = top_customers(orders, 5)
  [totals.size, top]
end

Timing by hand

Before you reach for a profiler, check how long the code takes. Use the monotonic clock, not Time.now. Time.now can jump when the system clock is adjusted:

require_relative "report"

t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
build_report(100_000)
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
puts "build_report: #{(elapsed * 1000).round(1)} ms"
build_report: 1810.5 ms

That is slow for 100,000 records, but this doesn't tell us which part is slow.

stackprof: sampling CPU profiler

stackprof interrupts the program at a fixed interval and records the current call stack. Methods that show up in many samples are where the time goes.

require "stackprof"
require_relative "report"

StackProf.run(mode: :cpu, out: "tmp/stackprof-cpu.dump", raw: true) do
  build_report(100_000)
end

raw: true keeps the full stacks, which you need to generate flame graphs later. Read the dump with the stackprof command:

$ stackprof tmp/stackprof-cpu.dump --text --limit 6
==================================
  Mode: cpu(1000)
  Samples: 387 (0.00% miss rate)
  GC: 13 (3.36%)
==================================
     TOTAL    (pct)     SAMPLES    (pct)     FRAME
       349  (90.2%)         209  (54.0%)     Object#top_customers
       347  (89.7%)         138  (35.7%)     Array#select
        15   (3.9%)          15   (3.9%)     String#gsub
        11   (2.8%)          11   (2.8%)     (marking)
         3   (0.8%)           3   (0.8%)     String#downcase
         2   (0.5%)           2   (0.5%)     (sweeping)

The two columns mean:

top_customers accounts for 90% of the total time. The (marking) and (sweeping) rows are garbage collection.

Zooming into a method

--method shows the callers, the callees and the source annotated with sample counts per line:

$ stackprof tmp/stackprof-cpu.dump --method top_customers
Object#top_customers (report.rb:17)
  samples:   209 self (54.0%)  /    349 total (90.2%)
  callers:
     349  (  100.0%)  Object#build_report
     347  (   99.4%)  Array#map
     209  (   59.9%)  Array#select
  callees (140 total):
     348  (  248.6%)  Array#map
     347  (  247.9%)  Array#select
       1  (    0.7%)  Array#uniq
  code:
                                  |    17  | def top_customers(orders, k)
                                  |    18  |   # O(n * m): scans all orders for every customer
    2    (0.5%)                   |    19  |   customers = orders.map(&:customer).uniq
  903  (233.3%) /   209  (54.0%)  |    20  |   customers.map { |c| [c, orders.select { |o| o.customer == c }.sum(&:amount)] }

Line 20 is the problem. For each of 500 customers it scans all 100,000 orders, which is 50 million comparisons. (The percentages go above 100% because nested blocks on the same line are counted once per stack frame.)

Fixing it and measuring again

Replace the nested scan with one pass over the orders:

def top_customers(orders, k)
  totals = Hash.new(0)
  orders.each { |o| totals[o.customer] += o.amount }
  totals.max_by(k) { |_, total| total }
end
build_report: 152.9 ms

That's 12x faster. If you profile again, top_customers drops off the top of the list and String#gsub in slugify becomes the hottest spot. Profiling is a loop: fix the biggest problem, re-profile, and stop when the program is fast enough.

Modes

Mode Samples on Use for
:cpu CPU time used by the process Computation-heavy code
:wall Elapsed real time Code that waits on I/O, sleep, locks, database calls
:object Every Nth object allocation Finding where objects are allocated

A :cpu profile doesn't show time spent waiting. A web request that spends 200 ms waiting on the database looks almost free in :cpu mode. Use :wall for anything that does I/O.

:object mode counts allocations instead of time:

StackProf.run(mode: :object, out: "tmp/stackprof-object.dump") do
  totals_by_customer(load_orders(100_000))
end
$ stackprof tmp/stackprof-object.dump --text --limit 4
==================================
  Mode: object(1)
  Samples: 1099020 (0.00% miss rate)
  GC: 0 (0.00%)
==================================
     TOTAL    (pct)     SAMPLES    (pct)     FRAME
    500000  (45.5%)      500000  (45.5%)     String#gsub
    298008  (27.1%)      298006  (27.1%)     Object#load_orders
    200000  (18.2%)      200000  (18.2%)     String#downcase
    800001  (72.8%)      100001   (9.1%)     Object#slugify

Each slugify call allocates 8 objects. Caching slugs per customer would remove most of them.

Start/stop API and results as data

If the code you want to profile isn't in a single block, use start and stop. StackProf.results returns a plain Hash, so you can process it in code:

require "stackprof"
require_relative "report"

StackProf.start(mode: :wall, interval: 500) # sample every 0.5 ms
build_report(20_000)
StackProf.stop

results = StackProf.results
puts results[:samples]
top = results[:frames].values.max_by { |f| f[:samples] }
puts "#{top[:name]}: #{top[:samples]} samples"
634
Array#select: 288 samples

The interval is in microseconds for :cpu and :wall (default 1000), and in allocations for :object. Smaller intervals give more samples and more overhead.

Profiling a whole script

You don't have to change the code at all. stackprof run loads the profiler into any Ruby command:

$ stackprof run --mode=cpu --out=tmp/run.dump -- ruby main.rb
StackProf results dumped at: tmp/run.dump

Flame graphs

A flame graph shows every stack as a horizontal bar, with width proportional to time. It's the fastest way to understand a deep call tree:

$ stackprof tmp/stackprof-cpu.dump --d3-flamegraph > tmp/flame.html

Open tmp/flame.html in a browser. This needs a profile recorded with raw: true. You can also upload stackprof --json output to speedscope.app.

Vernier: modern sampling profiler

Vernier is a newer sampling profiler. Compared to stackprof it:

require "vernier"
require_relative "report"

Vernier.profile(out: "tmp/report.vernier.json") do
  build_report(100_000)
end

To view the profile, open profiler.firefox.com and load the file. You get a call tree, a flame graph and a per-thread timeline. To look at it in the terminal instead, use vernier view:

$ vernier view --top 4 tmp/report.vernier.json
+---------+------+---------------------------+
| Samples | %    | name                      |
+---------+------+---------------------------+
| 1616    | 49.7 | Object#top_customers      |
| 1369    | 42.1 | Array#select              |
| 137     | 4.2  | String#gsub               |
| 28      | 0.9  | Object#load_orders        |
+---------+------+---------------------------+
================================================================================
report.rb
--------------------------------------------------------------------------------
 TOTAL |  SELF  | LINE SOURCE
...
  5.0% |   0.3% |    9    name.downcase.gsub(/[^a-z0-9]+/, "-")
...
233.9% |  49.7% |   20    customers.map { |c| [c, orders.select { |o| o.customer == c }.sum(&:amount)] }

Like stackprof, Vernier can wrap a whole command:

$ vernier run -- ruby main.rb
starting profiler with interval 500 and allocation interval 0
#<Vernier::Result 1.849931656 seconds, 1 threads, 1788 samples, 19 unique>
written to /home/me/app/profile-20261017-192459-1973.vernier.json.gz

Use start_profile and stop_profile when the code isn't in one block. Vernier is most useful for threaded code, where the timeline shows which threads were running and which were blocked:

require "vernier"
require_relative "report"

Vernier.start_profile(out: "tmp/threads.vernier.json", interval: 1000)
threads = [
  Thread.new { build_report(20_000) },   # CPU-bound
  Thread.new { 3.times { sleep 0.1 } }   # waiting
]
threads.each(&:join)
Vernier.stop_profile

Vernier samples wall time by default. Vernier.profile(mode: :retained) instead records which allocations are still alive at the end of the block, which helps you find memory leaks.

ruby-prof: tracing profiler

ruby-prof records every method call. That gives you exact call counts and a full call graph, but the program runs much slower:

require "ruby-prof"
require_relative "report"

profile = RubyProf::Profile.new(measure_mode: RubyProf::WALL_TIME)
result = profile.profile do
  build_report(20_000)
end

RubyProf::FlatPrinter.new(result).print($stdout, min_percent: 2)
Measure Mode: wall_time
Thread ID: 24
Fiber ID: 16
Total: 3.522408
Sort by: self_time

 %self      total      self      wait     child     calls  name
 62.09      3.458     2.187     0.000     1.271      500   Array#select
 18.84      0.664     0.664     0.000     0.000 10000000   String#==
 17.30      0.609     0.609     0.000     0.000 10040000   Order#customer

The call counts make the cause obvious: 10 million string comparisons. But notice the total: 3.5 seconds. Without the profiler, build_report(20_000) takes 0.3 seconds. The overhead is about 12x, and it falls mostly on tiny methods like String#== and Order#customer. Their share of the time is inflated compared to reality. Use ruby-prof for call counts and the shape of the call graph. Use a sampling profiler to find out where the time really goes.

Measure modes

Constant Measures
RubyProf::WALL_TIME Elapsed real time (default)
RubyProf::PROCESS_TIME CPU time used by the process
RubyProf::ALLOCATIONS Number of objects allocated
RubyProf::MEMORY Bytes allocated
result = RubyProf::Profile.profile(measure_mode: RubyProf::ALLOCATIONS) do
  totals_by_customer(load_orders(10_000))
end
RubyProf::FlatPrinter.new(result).print($stdout, min_percent: 5)
 %self      total      self      wait     child     calls  name
 39.68  40000.000 40000.000     0.000     0.000    10000   String#gsub
 29.56  29801.000 29801.000     0.000     0.000        1   Array#initialize
 19.84  20000.000 20000.000     0.000     0.000    10000   String#downcase
  9.92  70000.000 10000.000     0.000 60000.000    10000   Object#slugify

Printers and excluding noise

Iterators like Array#each, Array#map and Integer#times show up everywhere and clutter the report. exclude_common_methods! merges their time into their callers. Then you see which of your methods is slow:

profile = RubyProf::Profile.new(measure_mode: RubyProf::WALL_TIME)
profile.exclude_common_methods!
profile.start
build_report(20_000)
result = profile.stop

RubyProf::GraphPrinter.new(result).print($stdout, min_percent: 5)
File.open("tmp/graph.html", "w") { |f| RubyProf::GraphHtmlPrinter.new(result).print(f) }
File.open("tmp/stack.html", "w") { |f| RubyProf::CallStackPrinter.new(result).print(f) }
  %total   %self      total       self       wait      child            calls     name
--------------------------------------------------------------------------------------------
                      4.380      0.000      0.000      4.380              1/1     [global]#
 100.00%   0.00%      4.380      0.000      0.000      4.380                1     Object#build_report
                      4.322      2.730      0.000      1.593              1/1     Object#top_customers
                      0.039      0.007      0.000      0.032              1/1     Object#totals_by_customer
                      0.019      0.000      0.000      0.019              1/1     Object#load_orders
--------------------------------------------------------------------------------------------

Each block in the graph report shows one method, with its callers above it and its callees below. Array#select and Array#map are gone, and their time now counts as top_customers's own time.

Other printers: CallStackPrinter writes an interactive HTML call tree, CallTreePrinter writes callgrind files for KCachegrind or QCachegrind, and MultiPrinter writes several formats at once.

memory_profiler: where objects come from

Memory problems come in two kinds:

memory_profiler reports both, grouped by gem, file, line and class:

require "memory_profiler"
require_relative "report"

report = MemoryProfiler.report(top: 5) do
  totals_by_customer(load_orders(10_000))
end
report.pretty_print(scale_bytes: true)
Total allocated: 5.50 MB (90803 objects)
Total retained:  0 B (0 objects)

allocated memory by location
-----------------------------------
   4.08 MB  report.rb:9
   1.27 MB  report.rb:5
 134.50 kB  report.rb:13
  14.42 kB  report.rb:14

allocated memory by class
-----------------------------------
   3.21 MB  String
   1.68 MB  MatchData
 400.00 kB  Order
 180.04 kB  Array
  28.91 kB  Hash
...

Line 9 (slugify) allocates 74% of the memory, mostly strings and MatchData objects created by gsub. Nothing is retained, so there is no leak, only allocation churn.

Here is a leak. A cache that is never cleared keeps every value alive:

require "memory_profiler"

CACHE = {}

def lookup(key)
  CACHE[key] ||= "value for #{key}" * 10
end

report = MemoryProfiler.report do
  1_000.times { |i| lookup(i) }      # 1,000 distinct keys, all kept
  1_000.times { |i| "temp #{i}" }    # garbage, freed right away
end

puts "allocated: #{report.total_allocated} objects, #{report.total_allocated_memsize} bytes"
puts "retained:  #{report.total_retained} objects, #{report.total_retained_memsize} bytes"
allocated: 4980 objects, 319200 bytes
retained:  1000 objects, 160000 bytes

The "retained memory by location" section of pretty_print points straight at line 6. Useful pretty_print options:

MemoryProfiler.report also accepts allow_files: "app/" and ignore_files: /gems/ to filter the report.

Built-in tools

You can learn a lot without installing any gems.

GC statistics

GC.stat contains counters for the whole process. Take the difference before and after a block of code:

require_relative "report"

def gc_profile
  GC.start
  before = GC.stat
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  yield
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
  after = GC.stat
  {
    wall_ms:   (elapsed * 1000).round,
    gc_ms:     after[:time] - before[:time],
    gc_runs:   after[:count] - before[:count],
    minor:     after[:minor_gc_count] - before[:minor_gc_count],
    major:     after[:major_gc_count] - before[:major_gc_count],
    allocated: after[:total_allocated_objects] - before[:total_allocated_objects]
  }
end

p gc_profile { totals_by_customer(load_orders(200_000)) }
{wall_ms: 324, gc_ms: 59, gc_runs: 17, minor: 14, major: 3, allocated: 2197029}

Here 18% of the time goes to the garbage collector. GC.stat(:time) is the total GC time in milliseconds. If GC time is a large share of the total, reduce allocations before you optimize anything else.

Allocation sites with ObjectSpace

objspace can record the file, line and method where each object was created:

require "objspace"
require_relative "report"

ObjectSpace.trace_object_allocations_start
orders = load_orders(3)
slug = slugify(orders.first.customer)
ObjectSpace.trace_object_allocations_stop

[orders.first, slug].each do |obj|
  file = File.basename(ObjectSpace.allocation_sourcefile(obj))
  line = ObjectSpace.allocation_sourceline(obj)
  meth = ObjectSpace.allocation_method_id(obj)
  puts "#{obj.inspect} allocated at #{file}:#{line} in #{meth}"
end
puts "Order size: #{ObjectSpace.memsize_of(orders.first)} bytes"
#<struct Order id=0, customer="customer-0", amount=0> allocated at report.rb:5 in load_orders
"customer-0" allocated at report.rb:9 in gsub
Order size: 40 bytes

For a long-running process, ObjectSpace.dump_all(output: File.open("heap.json", "w")) writes every live object to a file. Take two dumps some time apart, and the objects that appear only in the second one are leak candidates. heapy and sheap are gems for analyzing these dumps.

Counting calls with TracePoint

TracePoint gives you the same events ruby-prof uses. A simple call counter takes a few lines:

require_relative "report"

calls = Hash.new(0)
trace = TracePoint.new(:call, :c_call) do |tp|
  calls["#{tp.defined_class}##{tp.method_id}"] += 1
end

trace.enable { build_report(2_000) }

calls.sort_by { |_, n| -n }.first(5).each do |name, n|
  puts format("%10d  %s", n, name)
end
   1004000  Order#customer
   1000000  String#==
      4000  Order#amount
      4000  Integer#%
      2000  Integer#*

:call fires for methods written in Ruby and :c_call for methods implemented in C. Like any tracer, this slows the program down a lot.

Profiling web applications

Profile in an environment that matches production. In Rails that means RAILS_ENV=production or at least config.eager_load = true and caching turned on. In development, code reloading and lazy loading take most of the time, and they hide the real problems.

Tips and pitfalls

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents