Source

RubyLearning / ProjectTrak / vendor / rails / railties / doc / guides / source / benchmarking_and_profiling / index.txt

Benchmarking and Profiling Rails
================================

This guide covers the benchmarking and profiling tactics/tools of Rails and Ruby in general. By referring to this guide, you will be able to:

* Understand the various types of benchmarking and profiling metrics
* Generate performance/benchmarking tests
* Use GC patched Ruby binary to measure memory usage and object allocation
* Understand the information provided by Rails inside the log files
* Learn about various tools facilitating benchmarking and profiling

== Why Benchmark and Profile ?

Benchmarking and Profiling is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a plesant browsing experience to the end users and cutting cost of unnecessary hardwares is important for any web application.

=== What is the difference between benchmarking and profiling ? ===

Benchmarking is the process of finding out if a piece of code is slow or not. Whereas profiling is the process of finding out what exactly is slowing down that piece of code.

== Using and understanding the log files ==

Rails logs files containt basic but very useful information about the time taken to serve every request. A typical log entry looks something like :

[source, ruby]
----------------------------------------------------------------------------
Processing ItemsController#index (for 127.0.0.1 at 2008-10-17 00:08:18) [GET]
  Session ID: BAh7BiIKZmxhc2hJQzonQWN0aHsABjoKQHVzZWR7AA==--83cff4fe0a897074a65335
  Parameters: {"action"=>"index", "controller"=>"items"}
Rendering template within layouts/items
Rendering items/index
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items]
----------------------------------------------------------------------------

For this section, we're only interested in the last line from that log entry:

[source, ruby]
----------------------------------------------------------------------------
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items]
----------------------------------------------------------------------------

This data is fairly straight forward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.

== Helper methods ==

Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a specific code. The method is called +benchmark()+ in all three components.

[source, ruby]
----------------------------------------------------------------------------
Project.benchmark("Creating project") do
  project = Project.create("name" => "stuff")
  project.create_manager("name" => "David")
  project.milestones << Milestone.find(:all)
end
----------------------------------------------------------------------------

The above code benchmarks the multiple statments enclosed inside +Project.benchmark("Creating project") do..end+ block and prints the results inside log files. The statement inside log files will look like:

[source, ruby]
----------------------------------------------------------------------------
Creating projectem (185.3ms)
----------------------------------------------------------------------------

Please refer to http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001336[API docs] for optional options to +benchmark()+

Similarly, you could use this helper method inside http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[controllers] ( Note that it's a class method here ):

[source, ruby]
----------------------------------------------------------------------------
def process_projects
  self.class.benchmark("Processing projects") do
    Project.process(params[:project_ids])
    Project.update_cached_projects
  end
end
----------------------------------------------------------------------------

and http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[views]:

[source, ruby]
----------------------------------------------------------------------------
<% benchmark("Showing projects partial") do %>
  <%= render :partial => @projects %>
<% end %>
----------------------------------------------------------------------------

== Performance Test Cases ==

Rails provides a very easy to write performance test cases, which look just like the regular integration tests.

If you have a look at +test/performance/browsing_test.rb+ in a newly created Rails application:

[source, ruby]
----------------------------------------------------------------------------
require 'test_helper'
require 'performance_test_help'

# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionController::PerformanceTest
  def test_homepage
    get '/'
  end
end
----------------------------------------------------------------------------

This is an automatically generated example performance test file, for testing performance of homepage('/') of the application.

=== Modes ===

==== Benchmarking ====
==== Profiling ====

=== Metrics ===

==== Process Time ====

CPU Cycles.

==== Memory ====

Memory taken.

==== Objects ====

Objects allocated.

==== GC Runs ====

Number of times the Ruby GC was run.

==== GC Time ====

Time spent running the Ruby GC.

=== Preparing Ruby and Ruby-prof ===

Before we go ahead, Rails performance testing requires you to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time. This process is very straight forward. If you've never compiled a Ruby binary before, you can follow the following steps to build a ruby binary inside your home directory:

==== Compile ====

[source, shell]
----------------------------------------------------------------------------
[lifo@null ~]$ mkdir rubygc
[lifo@null ~]$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p111.tar.gz
[lifo@null ~]$ tar -xzvf ruby-1.8.6-p111.tar.gz
[lifo@null ~]$ cd ruby-1.8.6-p111
[lifo@null ruby-1.8.6-p111]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
[lifo@null ruby-1.8.6-p111]$ ./configure --prefix=/Users/lifo/rubygc
[lifo@null ruby-1.8.6-p111]$ make && make install
----------------------------------------------------------------------------

==== Prepare aliases ====

Add the following lines in your ~/.profile for convenience:

----------------------------------------------------------------------------
alias gcruby='/Users/lifo/rubygc/bin/ruby'
alias gcrake='/Users/lifo/rubygc/bin/rake'
alias gcgem='/Users/lifo/rubygc/bin/gem'
alias gcirb='/Users/lifo/rubygc/bin/irb'
alias gcrails='/Users/lifo/rubygc/bin/rails'
----------------------------------------------------------------------------

==== Install rubygems and some basic gems ====

----------------------------------------------------------------------------
[lifo@null ~]$ wget http://rubyforge.org/frs/download.php/38646/rubygems-1.2.0.tgz
[lifo@null ~]$ tar -xzvf rubygems-1.2.0.tgz
[lifo@null ~]$ cd rubygems-1.2.0
[lifo@null rubygems-1.2.0]$ gcruby setup.rb
[lifo@null rubygems-1.2.0]$ cd ~
[lifo@null ~]$ gcgem install rake
[lifo@null ~]$ gcgem install rails
----------------------------------------------------------------------------

==== Install MySQL gem ====

----------------------------------------------------------------------------
[lifo@null ~]$ gcgem install mysql
----------------------------------------------------------------------------

If this fails, you can try to install it manually:

----------------------------------------------------------------------------
[lifo@null ~]$ cd /Users/lifo/rubygc/lib/ruby/gems/1.8/gems/mysql-2.7/
[lifo@null mysql-2.7]$ gcruby extconf.rb --with-mysql-config
[lifo@null mysql-2.7]$ make && make install
----------------------------------------------------------------------------

=== Installing Jeremy Kemper's ruby-prof ===

We also need to install Jeremy's ruby-prof gem using our newly built ruby:

[source, shell]
----------------------------------------------------------------------------
[lifo@null ~]$ git clone git://github.com/jeremy/ruby-prof.git
[lifo@null ~]$ cd ruby-prof/
[lifo@null ruby-prof (master)]$ gcrake gem
[lifo@null ruby-prof (master)]$ gcgem install pkg/ruby-prof-0.6.1.gem
----------------------------------------------------------------------------

=== Generating performance test ===

Rails provides a simple generator for creating new performance tests:

[source, shell]
----------------------------------------------------------------------------
[lifo@null application (master)]$ script/generate performance_test homepage
----------------------------------------------------------------------------

This will generate +test/performance/homepage_test.rb+:

[source, ruby]
----------------------------------------------------------------------------
require 'test_helper'
require 'performance_test_help'

class HomepageTest < ActionController::PerformanceTest
  # Replace this with your real tests.
  def test_homepage
    get '/'
  end
end
----------------------------------------------------------------------------

Which you can modify to suit your needs.

=== Running tests ===

include::rubyprof.txt[]

include::digging_deeper.txt[]

include::gameplan.txt[]

include::appendix.txt[]

== Changelog ==

http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4[Lighthouse ticket]

* October 17, 2008: First revision by Pratik
* September 6, 2008: Initial version by Matthew Bergman <MzbPhoto@gmail.com>