Ruby 对运行多次的行进行基准测试
Ruby Benchmarking a line that runs multiple times
假设我有一个超时的脚本,并且我想查看它花费大部分时间的地方。我知道我可以对任何给定的代码行进行基准测试,但我的理解是,如果我这样做:
Benchmark.measure { test = "a"*1_000_000 }
它将测量每次到达该线所花费的时间。但我想知道我的程序的哪些部分导致整体速度下降,被多次调用。有没有一种简单的方法可以在基准测试程序的整个过程中将行组合在一起?
更新:现在意识到这里的正确术语是分析而不是基准测试。
有许多 gem 可能对您的应用有帮助,但您可以尝试其中的一些:
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
假设我有一个超时的脚本,并且我想查看它花费大部分时间的地方。我知道我可以对任何给定的代码行进行基准测试,但我的理解是,如果我这样做:
Benchmark.measure { test = "a"*1_000_000 }
它将测量每次到达该线所花费的时间。但我想知道我的程序的哪些部分导致整体速度下降,被多次调用。有没有一种简单的方法可以在基准测试程序的整个过程中将行组合在一起?
更新:现在意识到这里的正确术语是分析而不是基准测试。
有许多 gem 可能对您的应用有帮助,但您可以尝试其中的一些:
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