这个是 Rails 官方的 Gem,可以直接集成到 Rails 里面
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
然后可以执行
$ 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
$ perftest profiler 'User.first' --runs 3
ProfilerTest#test_user_first (3 ms warmup)
process_time: 4 ms
memory: 289 Bytes
objects: 551
# 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 将会输出
# 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)