Ruby 正数をインクリメントする「+=」と「next」と「succ」のパフォーマンスを計測する

Ruby 正数をインクリメントする「+=」と「next」と「succ」のパフォーマンスを計測する

Rubyで、benchmarkを使用して、正数をインクリメントする「+=」と「next」と「succ」のパフォーマンスを計測するサンプルコードを記述してます。rubyのバージョンは2.7.2を使用してます。

環境

  • OS windows10 pro 64bit
  • ruby 2.7.2p137

パフォーマンス計測

benchmarkを使用して、数字の1を1000万回インクリメントした「+=」と「next」と「succ」のパフォーマンスを計測するサンプルコードとなります。

require 'benchmark'

# 繰り返し回数 1000万回
i = 10000000

num_i = 1
num_n = 1
num_s = 1

# 10は、reportラベルに使用する桁数
Benchmark.bm 10 do |r|

  r.report '#+=' do
    i.times do
      num_i += 1
    end
  end

  r.report '#next' do
    i.times do
      num_n = num_n.next
    end
  end

  r.report '#suss' do
    i.times do
      num_s = num_s.succ
    end
  end

end

実行結果

<1回目>
                 user     system      total        real
#+=          0.531000   0.000000   0.531000 (  0.539760)
#next        0.781000   0.000000   0.781000 (  0.801314)
#suss        0.563000   0.000000   0.563000 (  0.569061)

<2回目>
                 user     system      total        real
#+=          0.500000   0.000000   0.500000 (  0.501039)
#next        0.718000   0.016000   0.734000 (  0.762640)
#suss        0.500000   0.000000   0.500000 (  0.499954)

<3回目>
                 user     system      total        real
#+=          0.562000   0.000000   0.562000 (  0.583664)
#next        0.656000   0.000000   0.656000 (  0.646810)
#suss        0.500000   0.000000   0.500000 (  0.499054)

「+=」と「succ」が少しパフォーマンスは良さそうです。