iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
1
自我挑戰組

Ruby on Rails 與它們相關的東西系列 第 14

Day14 - 在 Ruby 中使用 Benchmark 比較哪個方法比較快

前言

總算開始進入 Ruby 程式語言的世界中,再不寫點什麼,都快與鐵人賽報名的題目不相干,變成標題殺人惹 XD

後續 Ruby on Rails 的相關文章,假定讀者為已經有 CRUD 基礎上(或有工作經驗),進而分享,故不從環境建置等開始說起 (若有興趣想從頭學,可參考這篇環境建置 Windows 10 安裝 Ruby + Rails + Node.js + Git + postgresql,然後自學)


Benchmark

中文翻譯為「基準測試」,為 Ruby 內建的 module,用於評估程式的效能

情境

寫了一段程式,想到幾種寫法皆能做到一樣的事情,但想知道哪個效能比較好的話,可以用 Benchmark,在 Ruby 或 Ruby on Rails 中皆能使用

如何測試

以下這段有 3 種方法可以測試:

  1. 在 Ruby 的 irb 模式中,貼上以下的程式碼
  2. 在 Ruby on Rails 的 rails console (可縮寫成 rails c) 中,貼上以下的程式碼
  3. 將以下這段存成 test.rb 檔,在終端機輸入 ruby test.rb
# test.rb

require 'benchmark'

begin
# n 為要測試的次數
  n = 5000000
  y = Benchmark.bm do |x|
    x.report("<<    ") { n.times { [] << 'river' } }
    x.report("push  ") { n.times { [].push('river') } }
    x.report("concat") { n.times { [].concat(['river']) } }
    x.report("+     ") { n.times { [] + ['river'] } }
  end
end

顯示如下

name user system total real
<< 0.600000 0.000000 0.600000 ( 0.615966)
push 0.650000 0.000000 0.650000 ( 0.658296)
concat 1.230000 0.010000 1.240000 ( 1.234671)
+ 1.010000 0.000000 1.010000 ( 1.034694)

irb 測試的畫面

rails c 測試的畫面

小結

從上述情境中可以發現使用 << 效能比較好
但不等於 << 這方法是最好的,端看情境應用
尤其在 SQL Query 時,更是明顯

參考資料

Benchmark


鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10239641
medium 文章連結:https://link.medium.com/epApulKUS9
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主


上一篇
Day13 - 一些 Git 指令
下一篇
Day15 - 如何看自己打出去的 request 完整資訊,以 PostBin 和 Webhook.site 為例
系列文
Ruby on Rails 與它們相關的東西31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言