Last active
August 29, 2015 14:12
-
-
Save MitsunChieh/5191a66bb0b8298dc640 to your computer and use it in GitHub Desktop.
[Ruby] Benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Benchmark 是一個記錄程式運算時間的 Module | |
# 兩個基本指令 :measure, :bm, :bmbm | |
# 更多:http://www.ruby-doc.org/stdlib-2.0/libdoc/benchmark/rdoc/Benchmark.html#method-c-measure | |
require 'benchmark' | |
puts Benchmark.measure{ method_name } | |
# user system total real <- 不會有這一行 | |
# 1.033333 0.016667 1.016667 ( 0.492106) | |
n = 50000 | |
Benchmark.bm(7) do |x| # 7 是 label 的寬度 | |
x.report("for:") { for i in 1..n; a = "1"; end } # report()括號內的字串會變成表格的橫列名稱 | |
x.report("times:") { n.times do ; a = "1"; end } | |
x.report("upto:") { 1.upto(n) do ; a = "1"; end } | |
end | |
# user system total real | |
# for: 1.050000 0.000000 1.050000 ( 0.503462) | |
# times: 1.533333 0.016667 1.550000 ( 0.735473) | |
# upto: 1.500000 0.016667 1.516667 ( 0.711239) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
@fibo_array = [] | |
def fibonacci(n) | |
@fibo_array[n] ||= (n < 2 ? n : fibonacci(n-1)+fibonacci(n-2)) | |
end | |
def fibonacci2(n) | |
def fibo(n) | |
prev, curr = 0, 1 | |
(n-1).times{ curr, prev = prev+curr, curr } | |
curr | |
end | |
n < 2 ? n : fibo(n) | |
end | |
Benchmark.bm(7) do |x| | |
n = 7000 | |
x.report("array:") { fibonacci(n) } | |
x.report("loop:") { fibonacci2(n) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment