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
    • 332
    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):

    1. User.benchmark("Creating user") do
    2. user = user.create("name" => "Jony")
    3. user.create_stories("content" => "Test")
    4. 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):

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

    Views(Action View):

    1. <% benchmark Show story feeds' do %>
    2. <%= show_story_feeds %>
    3. <% 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:

    1. <% benchmark Show story feeds' , level: :debug do %>
    2. <%= show_story_feeds %>
    3. <% 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
Reset Password
Fill out the form below and reset your password: