我编写了一个小型基准测试类来测试我的代码进行开发。目前我必须将类添加到每个方法的开头和结尾。是否可以预先添加、附加,这样我就不必弄乱我的代码了?
class ApplicationController
before_filter :init_perf
after_filter :write_perf_results_to_log!
def init_perf
@perf ||= Perf.new
end
def write_perf_results_to_log!
@perf.results
end
end
class Products < ApplicationsController
def foo
@perf.log(__methond__.to_s)
caculation = 5 *4
@perf.write!
end
def bar
@perf.log(__methond__.to_s)
caculation = 1 / 5
@perf.write!
end
end
这是 Perf 类。它位于服务文件夹中。
class Perf
def initialize
@results = []
end
def log(note)
@start = Time.now
@note = note
end
def write!
if @results.find {|h| h[:note] == @note } # Update :sec method exists in results
@results.select { |h| h["note"] == @note; h[":sec"] = (Time.now - @start).round(3) }
else # Add new Hash to results
@results << { :note => @note, :sec => (Time.now - @start).round(3) }
end
end
def results
content = "
PERFORMANCE STATISTICS!
"
@results.each do |r|
content += r[:note] + " " + r[:sec].to_s + "
"
end
content += "
"
Rails.logger.info content
end
end