方法
实例公共方法
benchmark(message = "Benchmarking", options = {}, &block) 链接
允许你在模板中测量一个代码块的执行时间,并将结果记录到日志中。将此代码块包装在耗时操作或潜在瓶颈周围,以获取操作的时间读数。例如,假设你认为你的文件处理方法花费的时间太长;你可以将其包装在一个 benchmark 代码块中。
<% benchmark 'Process data files' do %> <%= expensive_files_operation %> <% end %>
这将向日志添加类似“处理数据文件 (345.2ms)”的内容,你可以使用它来比较代码优化时的时间。
你可以选择一个日志记录器级别(:debug、:info、:warn、:error)作为 :level 选项。默认日志记录器级别值为 :info。
<% benchmark 'Low-level files', level: :debug do %> <%= lowlevel_files_operation %> <% end %>
最后,你可以将 true 作为第三个参数传递,以静默代码块内的所有日志活动(除了计时信息)。这对于将嘈杂的代码块精简为只产生一条日志的单个语句非常有用。
<% benchmark 'Process data files', level: :info, silence: true do %> <%= expensive_and_chatty_files_operation %> <% end %>
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/benchmarkable.rb, line 37 def benchmark(message = "Benchmarking", options = {}, &block) if logger options.assert_valid_keys(:level, :silence) options[:level] ||= :info result = nil ms = ActiveSupport::Benchmark.realtime(:float_millisecond) do result = options[:silence] ? logger.silence(&block) : yield end logger.public_send(options[:level], "%s (%.1fms)" % [ message, ms ]) result else yield end end