• Stars
    star
    780
  • Rank 58,299 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Benchmark and profile your Rails apps

Performance Testing Rails Applications

This guide covers the various ways of performance testing a Ruby on Rails application.

After reading this guide, you will know:

  • The various types of benchmarking and profiling metrics.
  • How to generate performance and benchmarking tests.
  • How to install and use a GC-patched Ruby binary to measure memory usage and object allocation.
  • The benchmarking information provided by Rails inside the log files.
  • Various tools facilitating benchmarking and profiling.

Performance testing 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 pleasant browsing experience for end users and cutting the cost of unnecessary hardware is important for any non-trivial web application.


Installation

As of rails 4 performance tests are no longer part of the default stack. If you want to use performance tests simply follow these instructions.

Add this line to your application's Gemfile:

gem 'rails-perftest'

If you want to benchmark/profile under MRI or REE, add this line as well:

gem 'ruby-prof'

Now run bundle install and you're ready to go.

Performance Test Cases

Rails performance tests are a special type of integration tests, designed for benchmarking and profiling the test code. With performance tests, you can determine where your application's memory or speed problems are coming from, and get a more in-depth picture of those problems.

Generating Performance Tests

Rails provides a generator called performance_test for creating new performance tests:

$ rails generate performance_test homepage

This generates homepage_test.rb in the test/performance directory:

require 'test_helper'
require 'rails/performance_test_help'

class HomepageTest < ActionDispatch::PerformanceTest
  # Refer to the documentation for all available options
  # self.profile_options = { runs: 5, metrics: [:wall_time, :memory],
  #                          output: 'tmp/performance', formats: [:flat] }

  test "homepage" do
    get '/'
  end
end

Examples

Let's assume your application has the following controller and model:

# routes.rb
root to: 'home#dashboard'
resources :posts

# home_controller.rb
class HomeController < ApplicationController
  def dashboard
    @users = User.last_ten.includes(:avatars)
    @posts = Post.all_today
  end
end

# posts_controller.rb
class PostsController < ApplicationController
  def create
    @post = Post.create(params[:post])
    redirect_to(@post)
  end
end

# post.rb
class Post < ActiveRecord::Base
  before_save :recalculate_costly_stats

  def slow_method
    # I fire gallzilion queries sleeping all around
  end

  private

  def recalculate_costly_stats
    # CPU heavy calculations
  end
end

Controller Example

Because performance tests are a special kind of integration test, you can use the get and post methods in them.

Here's the performance test for HomeController#dashboard and PostsController#create:

require 'test_helper'
require 'rails/performance_test_help'

class PostPerformanceTest < ActionDispatch::PerformanceTest
  def setup
    # Application requires logged-in user
    login_as(:lifo)
  end

  test "homepage" do
    get '/dashboard'
  end

  test "creating new post" do
    post '/posts', post: { body: 'lifo is fooling you' }
  end
end

You can find more details about the get and post methods in the
Testing Rails Applications guide.

Model Example

Even though the performance tests are integration tests and hence closer to the request/response cycle by nature, you can still performance test pure model code.

Performance test for Post model:

require 'test_helper'
require 'rails/performance_test_help'

class PostModelTest < ActionDispatch::PerformanceTest
  test "creation" do
    Post.create body: 'still fooling you', cost: '100'
  end

  test "slow method" do
    # Using posts(:awesome) fixture
    posts(:awesome).slow_method
  end
end

Modes

Performance tests can be run in two modes: Benchmarking and Profiling.

Benchmarking

Benchmarking makes it easy to quickly gather a few metrics about each test run. By default, each test case is run 4 times in benchmarking mode.

To run performance tests in benchmarking mode:

$ rake test:benchmark

To run a single test pass it as TEST:

$ bin/rake test:benchmark TEST=test/performance/your_test.rb

Profiling

Profiling allows you to make an in-depth analysis of each of your tests by using an external profiler. Depending on your Ruby interpreter, this profiler can be native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each test case is run once in profiling mode.

To run performance tests in profiling mode:

$ rake test:profile

Metrics

Benchmarking and profiling run performance tests and give you multiple metrics. The availability of each metric is determined by the interpreter being usedβ€”none of them support all metricsβ€”and by the mode in use. A brief description of each metric and their availability across interpreters/modes is given below.

Wall Time

Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system.

Process Time

Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load.

CPU Time

Similar to process time, but leverages the more accurate CPU clock counter available on the Pentium and PowerPC platforms.

User Time

User time measures the amount of time the CPU spent in user-mode, i.e. within the process. This is not affected by other processes and by the time it possibly spends blocked.

Memory

Memory measures the amount of memory used for the performance test case.

Objects

Objects measures the number of objects allocated for the performance test case.

GC Runs

GC Runs measures the number of times GC was invoked for the performance test case.

GC Time

GC Time measures the amount of time spent in GC for the performance test case.

Metric Availability

Benchmarking
Interpreter Wall Time Process Time CPU Time User Time Memory Objects GC Runs GC Time
MRI yes yes yes no yes yes yes yes
REE yes yes yes no yes yes yes yes
Rubinius yes no no no yes yes yes yes
JRuby yes no no yes yes yes yes yes
Profiling
Interpreter Wall Time Process Time CPU Time User Time Memory Objects GC Runs GC Time
MRI yes yes no no yes yes yes yes
REE yes yes no no yes yes yes yes
Rubinius yes no no no no no no no
JRuby yes no no no no no no no

NOTE: To profile under JRuby you'll need to run export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api" before the performance tests.

Understanding the Output

Performance tests generate different outputs inside tmp/performance directory depending on their mode and metric.

Benchmarking

In benchmarking mode, performance tests generate two types of outputs.

Command Line

This is the primary form of output in benchmarking mode. Example:

BrowsingTest#test_homepage (31 ms warmup)
           wall_time: 6 ms
              memory: 437.27 KB
             objects: 5,514
             gc_runs: 0
             gc_time: 19 ms
CSV Files

Performance test results are also appended to .csv files inside tmp/performance. For example, running the default BrowsingTest#test_homepage will generate following five files:

  • BrowsingTest#test_homepage_gc_runs.csv
  • BrowsingTest#test_homepage_gc_time.csv
  • BrowsingTest#test_homepage_memory.csv
  • BrowsingTest#test_homepage_objects.csv
  • BrowsingTest#test_homepage_wall_time.csv

As the results are appended to these files each time the performance tests are run in benchmarking mode, you can collect data over a period of time. This can be very helpful in analyzing the effects of code changes.

Sample output of BrowsingTest#test_homepage_wall_time.csv:

measurement,created_at,app,rails,ruby,platform
0.00738224999999992,2009-01-08T03:40:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00755874999999984,2009-01-08T03:46:18Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00762099999999993,2009-01-08T03:49:25Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00603075000000008,2009-01-08T04:03:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00619899999999995,2009-01-08T04:03:53Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00755449999999991,2009-01-08T04:04:55Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00595999999999997,2009-01-08T04:05:06Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00740450000000004,2009-01-09T03:54:47Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00603150000000008,2009-01-09T03:54:57Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
0.00771250000000012,2009-01-09T15:46:03Z,,3.0.0,ruby-1.8.7.249,x86_64-linux

Profiling

In profiling mode, performance tests can generate multiple types of outputs. The command line output is always presented but support for the others is dependent on the interpreter in use. A brief description of each type and their availability across interpreters is given below.

Command Line

This is a very basic form of output in profiling mode:

BrowsingTest#test_homepage (58 ms warmup)
        process_time: 63 ms
              memory: 832.13 KB
             objects: 7,882
Flat

Flat output shows the metricβ€”time, memory, etcβ€”measure in each method. Check Ruby-Prof documentation for a better explanation.

Graph

Graph output shows the metric measure in each method, which methods call it and which methods it calls. Check Ruby-Prof documentation for a better explanation.

Tree

Tree output is profiling information in calltree format for use by kcachegrind and similar tools.

Output Availability
Flat Graph Tree
MRI yes yes yes
REE yes yes yes
Rubinius yes yes no
JRuby yes yes no

Tuning Test Runs

Test runs can be tuned by setting the profile_options class variable on your test class.

require 'test_helper'
require 'rails/performance_test_help'

class BrowsingTest < ActionDispatch::PerformanceTest
  self.profile_options = { runs: 5, metrics: [:wall_time, :memory] }

  test "homepage"
    get '/'
  end
end

In this example, the test would run 5 times and measure wall time and memory. There are a few configurable options:

Option Description Default Mode
:runs Number of runs. Benchmarking: 4, Profiling: 1 Both
:output Directory to use when writing the results. tmp/performance Both
:metrics Metrics to use. See below. Both
:formats Formats to output to. See below. Profiling

Metrics and formats have different defaults depending on the interpreter in use.

Interpreter Mode Default metrics Default formats
MRI/REE Benchmarking [:wall_time, :memory, :objects, :gc_runs, :gc_time] N/A
Profiling [:process_time, :memory, :objects] [:flat, :graph_html, :call_tree, :call_stack]
Rubinius Benchmarking [:wall_time, :memory, :objects, :gc_runs, :gc_time] N/A
Profiling [:wall_time] [:flat, :graph]
JRuby Benchmarking [:wall_time, :user_time, :memory, :gc_runs, :gc_time] N/A
Profiling [:wall_time] [:flat, :graph]

As you've probably noticed by now, metrics and formats are specified using a symbol array with each name underscored.

Performance Test Environment

Performance tests are run in the test environment. But running performance tests will set the following configuration parameters:

ActionController::Base.perform_caching = true
ActiveSupport::Dependencies.mechanism = :require if ActiveSupport::Dependencies.respond_to?(:mechanism=)
Rails.logger.level = ActiveSupport::Logger::INFO

As ActionController::Base.perform_caching is set to true, performance tests will behave much as they do in the production environment.

Installing GC-Patched MRI 1.x.x

Since Ruby 2 is now mainstream and handles garbage collection issues these docs have been cut. View older readme explaining how to install optimized Ruby 1 builds.

Command Line Tools

Writing performance test cases could be an overkill when you are looking for one time tests. Rails ships with two command line tools that enable quick and dirty performance testing:

benchmarker

Usage:

Usage: perftest benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]
    -r, --runs N                     Number of runs.
                                     Default: 4
    -o, --output PATH                Directory to use when writing the results.
                                     Default: tmp/performance
    -m, --metrics a,b,c              Metrics to use.
                                     Default: wall_time,memory,objects,gc_runs,gc_time

Example:

$ perftest benchmarker 'Item.all' 'CouchItem.all' --runs 3 --metrics wall_time,memory

profiler

Usage:

Usage: perftest profiler 'Ruby.code' 'Ruby.more_code' ... [OPTS]
    -r, --runs N                     Number of runs.
                                     Default: 1
    -o, --output PATH                Directory to use when writing the results.
                                     Default: tmp/performance
    -m, --metrics a,b,c              Metrics to use.
                                     Default: process_time,memory,objects
    -f, --formats x,y,z              Formats to output to.
                                     Default: flat,graph_html,call_tree

Example:

$ perftest profiler 'Item.all' 'CouchItem.all' --runs 2 --metrics process_time --formats flat

NOTE: Metrics and formats vary from interpreter to interpreter. Pass --help to each tool to see the defaults for your interpreter.

Helper Methods

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

Model

Project.benchmark("Creating project") do
  project = Project.create("name" => "stuff")
  project.create_manager("name" => "David")
  project.milestones << Milestone.all
end

This benchmarks the code enclosed in the Project.benchmark("Creating project") do...end block and prints the result to the log file:

Creating project (185.3ms)

Please refer to the API docs for additional options to benchmark().

Controller

Similarly, you could use this helper method inside controllers.

def process_projects
  benchmark("Processing projects") do
    Project.process(params[:project_ids])
    Project.update_cached_projects
  end
end

NOTE: benchmark is a class method inside controllers.

View

And in views

<% benchmark("Showing projects partial") do %>
  <%= render @projects %>
<% end %>

Request Logging

Rails log files contain very useful information about the time taken to serve each request. Here's a typical log file entry:

Processing ItemsController#index (for 127.0.0.1 at 2009-01-08 03:06:39) [GET]
Rendering template within layouts/items
Rendering items/index
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]

For this section, we're only interested in the last line:

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

This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measure 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.

Useful Links

Rails Plugins and Gems

Generic Tools

Tutorials and Documentation

Commercial Products

Rails has been lucky to have a few companies dedicated to Rails-specific performance tools:

More Repositories

1

rails

Ruby on Rails
Ruby
55,483
star
2

webpacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
5,308
star
3

thor

Thor is a toolkit for building powerful command-line interfaces.
Ruby
5,115
star
4

jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
Ruby
4,324
star
5

spring

Rails application preloader
Ruby
2,804
star
6

jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
JavaScript
2,607
star
7

rails-dev-box

A virtual machine for Ruby on Rails core development
Shell
2,050
star
8

solid_queue

Database-backed Active Job backend
Ruby
1,709
star
9

tailwindcss-rails

Ruby
1,388
star
10

kredis

Higher-level data structures built on Redis
Ruby
1,376
star
11

activeresource

Connects business objects and REST web services
Ruby
1,322
star
12

docked

Running Rails from Docker for easy start to development
Dockerfile
1,291
star
13

strong_parameters

Taint and required checking for Action Pack and enforcement in Active Model
Ruby
1,270
star
14

globalid

Identify app models with a URI
Ruby
1,195
star
15

actioncable

Framework for real-time communication over websockets
1,084
star
16

importmap-rails

Use ESM with importmap to manage modern JavaScript in Rails without transpiling or bundling.
Ruby
1,037
star
17

jquery-rails

A gem to automate using jQuery with Rails
Ruby
947
star
18

sprockets

Rack-based asset packaging system
Ruby
937
star
19

sass-rails

Ruby on Rails stylesheet engine for Sass
Ruby
859
star
20

propshaft

Deliver assets for Rails
Ruby
855
star
21

exception_notification

NOTICE: official repository moved to https://github.com/smartinez87/exception_notification
Ruby
841
star
22

sdoc

Standalone sdoc generator
JavaScript
822
star
23

jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
Ruby
819
star
24

solid_cache

A database-backed ActiveSupport::Cache::Store
Ruby
786
star
25

activejob

Declare job classes that can be run by a variety of queueing backends
Ruby
744
star
26

activestorage

Store files in Rails applications
734
star
27

pjax_rails

PJAX integration for Rails
Ruby
667
star
28

actioncable-examples

Action Cable Examples
Ruby
663
star
29

cache_digests

Ruby
643
star
30

sprockets-rails

Sprockets Rails integration
Ruby
575
star
31

cssbundling-rails

Bundle and process CSS in Rails with Tailwind, PostCSS, and Sass via Node.js.
Ruby
568
star
32

activerecord-session_store

Active Record's Session Store extracted from Rails
Ruby
539
star
33

execjs

Run JavaScript code from Ruby
Ruby
528
star
34

rails-observers

Rails observer (removed from core in Rails 4.0)
Ruby
516
star
35

mission_control-jobs

Dashboard and Active Job extensions to operate and troubleshoot background jobs
Ruby
491
star
36

actiontext

Edit and display rich text in Rails applications
406
star
37

request.js

JavaScript
386
star
38

acts_as_list

NOTICE: official repository moved to https://github.com/swanandp/acts_as_list
Ruby
385
star
39

marcel

Find the mime type of files, examining file, filename and declared type
Ruby
383
star
40

rubocop-rails-omakase

Omakase Ruby styling for Rails
Ruby
380
star
41

actionpack-page_caching

Static page caching for Action Pack (removed from core in Rails 4.0)
Ruby
347
star
42

commands

Run Rake/Rails commands through the console
Ruby
337
star
43

ssl_requirement

NOTICE: official repository moved to https://github.com/retr0h/ssl_requirement
Ruby
315
star
44

rails-controller-testing

Brings back `assigns` and `assert_template` to your Rails tests
Ruby
303
star
45

rails-html-sanitizer

Ruby
302
star
46

open_id_authentication

NOTICE: official repository moved to https://github.com/Velir/open_id_authentication
Ruby
285
star
47

acts_as_tree

NOTICE: official repository moved to https://github.com/amerine/acts_as_tree
Ruby
281
star
48

actionpack-action_caching

Action caching for Action Pack (removed from core in Rails 4.0)
Ruby
260
star
49

in_place_editing

NOTICE: official repository moved to https://github.com/amerine/in_place_editing
Ruby
230
star
50

protected_attributes

Protect attributes from mass-assignment in ActiveRecord models.
Ruby
229
star
51

journey

A router for rails
Ruby
221
star
52

auto_complete

NOTICE: official repository moved to https://github.com/david-kerins/auto_complete
Ruby
211
star
53

dartsass-rails

Integrate Dart Sass with the asset pipeline in Rails
Ruby
206
star
54

dynamic_form

NOTICE: official repository moved to https://github.com/joelmoss/dynamic_form
Ruby
192
star
55

solid_cable

A database backed ActionCable adapter
Ruby
187
star
56

country_select

NOTICE: official repository moved to https://github.com/stefanpenner/country_select
Ruby
176
star
57

rails-dom-testing

Extracting DomAssertions and SelectorAssertions from ActionView.
Ruby
174
star
58

routing_concerns

Abstract common routing resource concerns to cut down on duplication.
Ruby
154
star
59

esbuild-rails

Bundle and transpile JavaScript in Rails with esbuild
Ruby
147
star
60

rails-contributors

The web application that runs https://contributors.rubyonrails.org
Ruby
138
star
61

rails-new

Create Rails projects with Ruby installed
Rust
125
star
62

actionmailbox

Receive and process incoming emails in Rails
125
star
63

requestjs-rails

JavaScript
119
star
64

activemodel-globalid

Serializing models to a single string makes it easy to pass references around
Ruby
90
star
65

account_location

NOTICE: official repository moved to https://github.com/bbommarito/account_location
Ruby
73
star
66

acts_as_nested_set

NOTICE: official repository moved to https://github.com/bbommarito/acts_as_nested_set
Ruby
71
star
67

iso-3166-country-select

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
70
star
68

activerecord-deprecated_finders

Ruby
68
star
69

spring-watcher-listen

Ruby
64
star
70

website

HTML
64
star
71

weblog

Superseded by https://github.com/rails/website
HTML
63
star
72

prototype-ujs

JavaScript
62
star
73

prototype_legacy_helper

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
Ruby
60
star
74

verification

NOTICE: official repository moved to https://github.com/sikachu/verification
Ruby
58
star
75

prototype-rails

Add RJS, Prototype, and Scriptaculous helpers to Rails 3.1+ apps
Ruby
55
star
76

activemodel-serializers-xml

Ruby
52
star
77

record_tag_helper

ActionView Record Tag Helpers
Ruby
51
star
78

homepage

Superseded by https://github.com/rails/website
HTML
50
star
79

rollupjs-rails

Bundle and transpile JavaScript in Rails with rollup.js
Ruby
49
star
80

actionpack-xml_parser

XML parameters parser for Action Pack (removed from core in Rails 4.0)
Ruby
49
star
81

activesupport-json_encoder

Ruby
48
star
82

etagger

Declare what goes in to your ETags: asset versions, account ID, etc.
Ruby
41
star
83

upload_progress

NOTICE: official repository moved to https://github.com/rishav/upload_progress
Ruby
39
star
84

devcontainer

Shell
38
star
85

atom_feed_helper

NOTICE: official repository moved to https://github.com/TrevorBramble/atom_feed_helper
Ruby
38
star
86

render_component

NOTICE: official repository moved to https://github.com/malev/render_component. Components allow you to call other actions for their rendered response while executing another action
Ruby
38
star
87

gsoc2014

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2014
37
star
88

gsoc2013

Project website and wiki for Ruby on Rails proposals to Google Summer of Code 2013
31
star
89

ruby-coffee-script

Ruby CoffeeScript Compiler
Ruby
28
star
90

asset_server

NOTICE: official repository moved to https://github.com/andhapp/asset_server
Ruby
27
star
91

homepage-2011

This repo is now legacy. New homepage is at rails/homepage
HTML
27
star
92

deadlock_retry

NOTICE: official repository moved to https://github.com/heaps/deadlock_retry
Ruby
27
star
93

rails-docs-server

Ruby
25
star
94

token_generator

NOTICE: official repository moved to https://github.com/bbommarito/token_generator
Ruby
25
star
95

http_authentication

NOTICE: official repository moved to https://github.com/dshimy/http_authentication
Ruby
22
star
96

irs_process_scripts

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. The extracted inspector, reaper, and spawner scripts from script/process/*
22
star
97

javascript_test

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
19
star
98

buildkite-config

Fallback configuration for branches that lack a .buildkite/ directory
Ruby
18
star
99

scriptaculous_slider

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core
JavaScript
18
star
100

request_profiler

WARNING: this repo is not maintained anymore, if you want to maintain it, please send an mail to rails-core. Request profiler based on integration test scripts
Ruby
17
star