Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

数値表現の違いによる速度差

Rubyで、100_000_000と書いても10**8と書いても1e8と書いても、そう大差はないと思っていたのですが、大きな間違いでした。

require 'benchmark'
Benchmark.bm(15) do |x|
  x.report("100_000_000") { 1.upto(100_000_000){}}
  x.report("10**8") { 1.upto(10**8){}}
  x.report("1e8") { 1.upto(1e8){}} 
end

実行結果

100_000_000と10**8はほぼ同じですが、1e8だと3倍弱ほど遅くなりますね。

                      user     system      total        real
100_000_000       8.680000   0.020000   8.700000 (  8.739381)
10**8             8.770000   0.000000   8.770000 (  8.825189)
1e8              21.990000   0.030000  22.020000 ( 22.030971)