Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created February 20, 2013 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/4991957 to your computer and use it in GitHub Desktop.
Save komasaru/4991957 to your computer and use it in GitHub Desktop.
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