我的rails应用程序中有各种耙子任务。下面显示了一个简单的示例。
desc "Simple rake task"
task :test_rake do |task|
first_sql_query = FirstModel.find(10)
SecondModel.create(:name => 'Test 101', :email => 'abc@def.co')
final_query = SecondModel.find(900)
end
现在在上面的 rake 任务中,我们进行了三次数据库调用,每个调用大约需要x
、y
、z
秒。
有没有办法找出给定的耙子任务在数据库操作上花费的总时间(x+y+z
秒(..??
使用benchmark
task :test_rake do |task|
time = Benchmark.realtime {
first_sql_query = FirstModel.find(10)
SecondModel.create(:name => 'Test 101', :email => 'abc@def.co')
final_query = SecondModel.find(900)
}
puts time
end
获取单独的基准:
puts Benchmark.measure { FirstModel.find(10) }
puts Benchmark.measure { SecondModel.create(:name => 'Test 101', :email => 'abc@def.co') }
puts Benchmark.measure { final_query = SecondModel.find(900) }
查询计时包含在日志文件中:
❯❯❯ rake db:migrate:status
database: ml_development
Status Migration ID Migration Name
--------------------------------------------------
up 20180612055823 ********** NO FILE **********
然后:
❯❯❯ cat log/development.log
[DEBUG] (0.4ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
'''
@pattu Rails 内部使用Benchmark
进行执行时间检查say_with_time 您可以在模块中添加相同的函数,并包含在机架任务中,以查找SQL查询的执行时间。
需要这两个函数:
def say(message, subitem = false)
puts "#{subitem ? " ->" : "--"} #{message}"
end
def say_with_time(message = "")
say(message)
result = nil
time = Benchmark.measure { result = yield }
say "%.4fs" % time.real, :subitem
say("#{result} rows", :subitem) if result.is_a?(Integer)
result
end
在您的耙子任务中将其用作
desc "Simple rake task"
task :test_rake do |task|
say_with_time do
first_sql_query = FirstModel.find(10)
SecondModel.create(:name => 'Test 101', :email => 'abc@def.co')
final_query = SecondModel.find(900)
end
end