0

Suppose I have a script that's timing out, and I want to see where it's spending most of its time. I know I can benchmark any given line of code, but my understanding is that if I do:

Benchmark.measure { test = "a"*1_000_000 }

That it will measure the time it takes every time that line is reached. But I want to know which parts of my program are causing the slowdown overall, being called multiple times. Is there an easy way to group lines together across the course of the program for Benchmarking?

Update: Realizing now the proper term here is profiling rather than benchmarking.

Ben G
  • 26,091
  • 34
  • 103
  • 170

1 Answers1

2

There are many gems that might help depending on your application but you could try some of these:

https://github.com/flyerhzm/bullet

https://github.com/SamSaffron/memory_profiler

https://github.com/MiniProfiler/rack-mini-profiler

https://github.com/tmm1/stackprof

https://github.com/oozou/ruby-prof-flamegraph

Another crude approach might be to add a Logger and log before and after any line which you suspect might be time consuming.

Let's use ruby-prof-flamegraph example:

Install the gem:

gem install ruby-prof-flamegraph

And the example implementation:

#example.rb

require 'ruby-prof'
require 'ruby-prof-flamegraph'

rubyprof_dir = Gem::Specification.find_by_name('ruby-prof').gem_dir
require "#{rubyprof_dir}/test/prime"

# Profile the code
result = RubyProf.profile do
  run_primes(200)
end

# Print a graph profile to text
printer = RubyProf::FlameGraphPrinter.new(result)
printer.print(STDOUT, {})

To generate the image:

bundle exec ruby example.rb | \
    ~/GitHub/FlameGraph/flamegraph.pl --countname=ms --width=728 > example.svg
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48