Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script for benchmarks.
require 'benchmark'
# 階乗を普通に計算
def fact_1(n)
f = 1
n == 0 ? f : (1..n).each {|i| f = f * i}
end
# 階乗を再帰的に計算
def fact_2(n)
n == 0 ? 1 : fact_2(n - 1) * n
end
# 階乗を Ruby ならではの inject を使って計算
def fact_3(n)
(1..n).to_a.inject(1) {|f, i| f * i}
end
# 実行回数、数字
cnt = 10 ** 3
num = 2 ** 10
# ヘッダキャプション
puts Benchmark::CAPTION
# 階乗を普通に計算
puts Benchmark.measure {cnt.times {res = fact_1(num)}}
# 階乗を再帰的に計算
puts Benchmark.measure {cnt.times {res = fact_2(num)}}
# 階乗を Ruby ならではの inject を使って計算
puts Benchmark.measure {cnt.times {res = fact_3(num)}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.