If your Rails application is taking longer than expected to load a specific page, use Active Support's Benchmarkable module to measure the code execution time in your view templates.
Here's the typical code you'd write to display the posts on your blog.
<% @posts.each do |post| %> <%= render post %> <% end %>
Let's say your home page, which displays the posts, is taking too long to load. To find how long it takes to execute this code, simply wrap it in the
<% benchmark 'Display posts' do %> <% @posts.each do |post| %> <%= render post %> <% end %> <% end %>
When you reload the above view, Rails will print the time taken to execute the above template with the label you provided.
Behind the scenes, the Benchmarkable module uses the
Benchmark class provided by the Ruby standard library, which we saw in my earlier post, How to Benchmark Ruby Code.
So this is how you can benchmark your Rails views. I hope you learned something new. I sure did. Let me know if you liked this post or have any feedback. I look forward to hearing from you.