1

我想大家都遇到过类似这样的一段代码:

def query(sql)
  logger.debug "Db: Executing query #{sql}"
  result = nil
  ts = Benchmark.realtime do
    result = @db.exec sql
  end
  logger.debug "Db: Query completed in #{ts}"
  result
end

坦率地说,这看起来很难看。有没有更优雅的方法来达到同样的效果?

4

1 回答 1

2

您可以编写自己的包装方法,如下所示并隐藏丑陋:

require 'benchmark'

def bm (description, &block)
  [].tap do |result|
  ts = Benchmark.realtime do
    result <<  block.call
  end
    p "#{description} completed in #{ts}"
  end.first
end

result =  bm("db query") {"db result"}
p result 

输出:

"db query completed in 5.131e-06"
"db result"
于 2012-10-12T13:29:29.437 回答