如何在Ruby中创建一个带有任意函数调用的简单计时器方法?
例如:
time rspec
或time get_primes(54784637)
它仍然应该返回传入的函数的结果(get_primes
)。
以下内容不太有效:
def time block
t = Time.now
result = eval(block)
puts "\nCompleted in #{(Time.now - t).format} seconds"
result
end
Ruby 1.9.3
答案 0 :(得分:5)
使用块的Rubaintque更多:
def time
t = Time.now
result = yield
puts "\nCompleted in #{Time.now - t} seconds"
result
end
time { rspec }
答案 1 :(得分:2)
试试这样:
def time(&block)
t = Time.now
result = block.call
puts "\nCompleted in #{(Time.now - t)} seconds"
result
end
答案 2 :(得分:2)
此功能已在Ruby的标准库中的Benchmark模块中提供:
require 'benchmark'
time = Benchmark.realtime { 10_000.times { print "a" } }