假设我有一个超时的脚本,我想看看它花费大部分时间在哪里。我知道我可以对任何给定的代码行进行基准测试,但我的理解是,如果我这样做:
Benchmark.measure { test = "a"*1_000_000 }
它将衡量每次到达该行所需的时间。但我想知道我的程序的哪些部分导致整体减速,被多次调用。有没有一种简单的方法可以在整个基准程序的过程中将线组合在一起?
更新:现在意识到正确的术语是分析而不是基准测试。
答案 0 :(得分:2)
根据您的应用程序,有许多宝石可能有所帮助,但您可以尝试其中一些:
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
另一种粗略的方法可能是在您怀疑可能耗费时间的任何行之前和之后添加Logger
和日志。
让我们使用ruby-prof-flamegraph
示例:
安装gem:
gem install ruby-prof-flamegraph
示例实现:
#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, {})
生成图片:
bundle exec ruby example.rb | \
~/GitHub/FlameGraph/flamegraph.pl --countname=ms --width=728 > example.svg