介绍如何对代码进行基准测试

65 阅读1分钟

在我们的应用程序中很容易意外地编写慢速代码。在本集中,我们将介绍如何对代码进行基准测试,以及一些比其他方法慢的方法的示例。

# benchmark.rb
require 'benchmark/ips'

n = 500_000
Benchmark.ips do |x|
  x.report('for') { for i in 1..n; a = '1'; end }
  x.report('times') { n.times do; a = '1'; end }
  x.report('upto') { 1.upto(n) do; a = '1'; end }
  x.compare!
end