LoginSignup
58

More than 5 years have passed since last update.

Rails で各処理のベンチマークを取る

Posted at

Rails だと直接 Benchmark クラスを使わなくても以下のようなヘルパが用意されている。
確認した Rails のバージョンは 4.1.6。

Controller

Controller 内で使いたい場合は以下のように書く。

def index
   benchmark("posts#index") do
     @posts = Post.all
   end
end

これで該当の action を実行すると以下のようにログに引数に渡した文字列と共に処理時間が表示される。

posts#index (2.6ms)

ログレベルを変更したい場合は以下のようにする。

benchmark("posts#index", level: :debug) do
  @posts = Post.all
end

Model

Model の場合はクラスメソッドになっている。

Post.benchmark("commented_post") do
  Post.joins(:comments).eager_load(:comments).all
end

以下のようにも書ける。

ActiveRecord::Base.benchmark("commented_post") do
  Post.joins(:comments).eager_load(:comments).all
end

View

View の場合は他の Helper メソッド等と同じで benchmark だけでいい。

<% benchmark("rendering posts") do %>
  <% @posts.each do |post| %>
    <tr>
      <td><%= link_to 'Show', post %></td>
      <td><%= link_to 'Edit', edit_post_path(post) %></td>
      <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
<% end %>

参考

benchmark (ActiveSupport::Benchmarkable) - APIdock
http://apidock.com/rails/ActiveSupport/Benchmarkable/benchmark

3 系用の RailsGuides だと以下の辺りに書いてあるけど 4 以降には書いて無いみたい。

3 Helper Methods
http://guides.rubyonrails.org/v3.2.19/performance_testing.html#helper-methods

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58