1

在 Rails 中能夠使用 explain + analyze

 2 years ago
source link: https://blog.niclin.tw/2018/07/04/%E5%9C%A8-rails-%E4%B8%AD%E8%83%BD%E5%A4%A0%E4%BD%BF%E7%94%A8-explain---analyze/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Nic Lin's Blog

喜歡在地上滾的工程師

平常開發 Rails 在效能瓶頸時,除了會進 Database 測 explain 以外,也會在 console 裡面下同樣的語句。

不過遺憾的是,Rails 只能夠單純用 explain 而已,在 Postgres 中,如果僅僅只用 explain 分析,可能不是那麼準確,因為 explain 只是單純推測 query plan。

但如果下 explain analyze 就不一樣了,他除了會有推測分析還會有實際執行的分析,因為是拿這條 query 下去跑並回傳優化器的結果。

用最簡單的方式可以在 Rails console 就能呼叫

query = "EXPLAIN ANALYZE #{User.order(:created_at).to_sql}"
ActiveRecord::Base.connection.execute(query).each {|result| puts result}

#   (10.0ms)  EXPLAIN ANALYSE SELECT "users".* FROM "users" ORDER BY "users"."created_at" ASC
# {"QUERY PLAN"=>"Sort  (cost=10.52..10.78 rows=104 width=843) (actual time=4.872..4.890 rows=104 loops=1)"}
# {"QUERY PLAN"=>"  Sort Key: created_at"}
# {"QUERY PLAN"=>"  Sort Method: quicksort  Memory: 79kB"}
# {"QUERY PLAN"=>"  ->  Seq Scan on users  (cost=0.00..7.04 rows=104 width=843) (actual time=3.266..4.181 rows=104 loops=1)"}
# {"QUERY PLAN"=>"Planning time: 3.441 ms"}
# {"QUERY PLAN"=>"Execution time: 4.978 ms"}
# #<PG::Result:0x00007fc9d224e390 status=PGRES_TUPLES_OK ntuples=6 nfields=1 cmd_tuples=0>

參考來源:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK