By default, Ruby on Rails logs out the time spent accessing the database and generating a View view.

(Views: 284.3ms | ActiveRecord: 112.1ms) 

In addition, the time of generation of each SQL query is displayed and the structure of ActiveRecord time is clear, but how can you decipher the structure of the time of generation of views (Views)?

  • Something really slows down the application? - Mal Skrylev
  • In production, where everything is cached - everything is fine, but locally against the background of the total load, yes, it happens to slow down, Views reaches 14 seconds, I would like to see what time is spent on. - cheops pm
  • not, such a slowdown is only in development, usually ruby-prof-ohm fix it =) - Mal Skrylev
  • Interesting, thanks, additional environment is required for profiling, it will be necessary to pick it up. Why not make a response? With your permission, I will place what I dug myself during these three days. - cheops

1 answer 1

For profiling, you can use the rack-mini-profiler gem in conjunction with the flamegraph gem, which graphically represents the results of the profiling. You can prepare the application as follows. In the gemfile, in the development environment we put both gems that we are going to use.

 group :development do ... gem 'rack-mini-profiler', require: false gem 'flamegraph' ... end 

Next, create the initialization file config / initializers / rack_profiler.rb with the following contents

 if Rails.env == 'development' require 'rack-mini-profiler' Rack::MiniProfilerRails.initialize!(Rails.application) end 

We run the application and get the results on any page of interest to us by adding the GET parameter? Pp = flamegraph to the address. As a result, a graphics card with gems will be displayed, where the rail application lists the maximum amount of time and the stack of method calls. Hovering the mouse on the line in the stack, leads to the conclusion of the path to the file and the method that is responsible for this section of the stack.

Graphic representation of the call stack in a Rails application

In addition, you can use the heme ActiveSupport , which is part of Ruby on Rails. In its simplest form, you can use the Benchmark class, which allows you to measure the time it takes to perform a particular operation:

 >> Benchmark.ms {Post.order (created_at:: desc) .limit (10)}
 => 0.134

If we use the benchmark method, then for the operation placed in the block

 collection = benchmark 'Exctracting posts collection', level :: debug do
   Post.order (created_at:: desc) .limit (10)
 end

You can get a report output on the operation execution time in the logs in the standard format for Rails:

 ...
 Exctracting posts collection (134.0ms)
 ...