LoginSignup
0
1

More than 5 years have passed since last update.

Rubyベンチマーク集

Posted at
  • 気になったものをどんどんベンチマークをとって比較していきます

ベンチマークテンプレート

  • ベンチマークのコードは共通なので、最初に書いておきます
require 'benchmark'

Benchmark.bmbm(10) do |r|
  r.report "test1" do
    # exec test1
  end
  r.report "test2" do
    99999999.times do |i|
      test2(i)
    end
  end
end

偶奇判定

コード

  • 先ずは奇数判定から
require 'benchmark'

def test1(n)
  n.odd?
end

def test2(n)
  n & 1 == 1
end

Benchmark.bmbm(10) do |r|
  r.report "test1" do
    99999999.times do |i|
      test1(i)
    end
  end
  r.report "test2" do
    99999999.times do |i|
      test2(i)
    end
  end
end

結果

  • odd?の方が早い
Rehearsal ----------------------------------------------
test1        7.950000   0.010000   7.960000 (  7.984393)
test2        8.820000   0.020000   8.840000 (  8.868345)
------------------------------------ total: 16.800000sec

                 user     system      total        real
test1        7.810000   0.010000   7.820000 (  7.841257)
test2        8.770000   0.020000   8.790000 (  8.803263)

コード

  • お次は偶数
def test1(n)
  n.even?
end

def test2(n)
  n & 1 == 0
end

結果

  • こちらもevenの方が早い
Rehearsal ----------------------------------------------
test1        8.240000   0.060000   8.300000 (  8.447544)
test2        9.810000   0.070000   9.880000 ( 10.163554)
------------------------------------ total: 18.180000sec

                 user     system      total        real
test1        8.190000   0.050000   8.240000 (  8.424226)
test2        9.430000   0.060000   9.490000 (  9.701474)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1