我的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
秒。
有没有办法找出给定rake任务在数据库操作上花费的总时间(x+y+z
秒)??
答案 0 :(得分:1)
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) }
答案 1 :(得分:0)
@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
在您的rake任务中将其用作
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
答案 2 :(得分:0)
查询时间包含在日志文件中
❯❯❯ 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
```