Ruby 「def」と「アロー演算子」のパフォーマンスを計測する
Rubyで、benchmarkを使用して、「def」と「アロー演算子」のパフォーマンスを計測するサンプルコードを記述してます。rubyのバージョンは2.7.2を使用してます。
環境
- OS windows10 pro 64bit
- ruby 2.7.2p137
パフォーマンス計測
benchmarkを使用して、「def」と「アロー演算子」を使用して、演算を行うコードを1億回呼び出したパフォーマンスを計測するサンプルコードとなります。
require "benchmark"
# 繰り返し回数 1億回
i = 100000000
# def
def calc1(x)
return x * 2
end
# アロー演算子
calc2 = ->x { x * 2 }
# 10は、reportラベルに使用する桁数
Benchmark.bm 10 do |r|
r.report "#def" do
i.times do
calc1(2)
end
end
r.report "#= ->" do
i.times do
calc2[2]
end
end
end
実行結果
<1回目>
user system total real
#def 4.282000 0.000000 4.282000 ( 4.284021)
#= -> 6.515000 0.000000 6.515000 ( 6.520583)
<2回目>
user system total real
#def 4.234000 0.000000 4.234000 ( 4.242139)
#= -> 9.172000 0.000000 9.172000 ( 9.159863)
<3回目>
user system total real
#def 4.453000 0.000000 4.453000 ( 4.471239)
#= -> 7.062000 0.000000 7.062000 ( 7.071492)
「def」が、パフォーマンスは良さそうです。
-
前の記事
php is_resourceでresource型であるかを判定する 2021.11.10
-
次の記事
AlmaLinuxに「VScode」をインストールする 2021.11.10
コメントを書く