Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Benchmark helper in rails

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 69
    Comment on it

    Rails has benchmark helper to quickly test the time of execution of a given piece of code. Active Record, Action Controller and Action View libraries provides a benchmark() method to measure the performance of code.

    Example: Model(Active Record):

    User.benchmark("Creating user") do
      user = user.create("name" => "Jony")
      user.create_stories("content" => "Test")
    end
    

    While execution of the above piece of code something like this Creating user (100.3ms) can be seen in the log file.Here benchmark() is a class method of the model User.

    Controller(Action Controller):

    def process_stories
      self.class.benchmark("Processing stories") do
        @stories = current_user.stories
        Story.cache_story_feeds(@stories, "myfeed-#{current_user.id}")
      end
    end
    

    Views(Action View):

        <% benchmark Show story feeds' do %>
              <%= show_story_feeds %>
        <% end %>
    
    

    In the log file output will be Show story feeds (191.5ms).

    This benchmark() method accepts logger level(:debug, :info, :warn, :error) as optional parameter. Default is :info. Thus we can modify the above code as:

    <% benchmark Show story feeds' , level: :debug do %>
              <%= show_story_feeds %>
        <% end %>
    

    If we pass silence: true as the third argument all logging activity except the time information for the block will be silenced.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: