这个是 Rails 官方的 Gem,可以直接集成到 Rails 里面

你可以写 Benchmark 的测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
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

然后可以执行

1
2
3
4
5
6
7
$ rake test:benchmark
HomepageTest#test_homepage (31 ms warmup)
           wall_time: 6 ms
              memory: 437.27 KB
             objects: 5,514
             gc_runs: 0
             gc_time: 19 ms

你可以直接在命令行使用

1
2
3
4
5
$ perftest profiler 'User.first' --runs 3
ProfilerTest#test_user_first (3 ms warmup)
        process_time: 4 ms
              memory: 289 Bytes
             objects: 551

你还可以用 Helper 在 View, Controler, Model 里面打点统计

1
2
3
4
5
6
7
8
9
# app/controllers/topics_controller.rb
class TopicsController < ApplicationController
  def index
    benchmark("  Benchmark: topics/index/suggest_topics") do
      @suggest_topics = Topic.without_hide_nodes.suggest.limit(3)
    end
    ...
  end
end

Rails log 将会输出

1
2
3
4
5
6
# development.log
Started GET "/topics" for 127.0.0.1 at 2015-01-01 00:50:19 +0800
  ...
  Benchmark:  topics/index/suggest_topics (1.4ms)
  ...
Completed 200 OK in 121ms (Views: 108.1ms)

还有更多功能待你发现哦!


https://github.com/rails/rails-perftest